regex - 如何使用 spacy 和 pandas 检查动词是否存在?

标签 regex pandas nltk spacy

import spacy, en_core_web_sm
nlp = en_core_web_sm.load()
doc = nlp(u"I will go to the mall")
chk_set = set(['VERB'])
print chk_set.issubset(t.pos_ for t in doc)

上面的代码返回True if POS = verb存在。

现在我想扩展此代码以读取 Excel 工作表中存储的句子列表。要检查句子中是否存在标点符号,我可以使用下面的代码来实现。

问题是如何扩展下面的代码以合并上面的动词检查。

from pandas import read_excel
import pandas as pd
import xlsxwriter
my_sheet_name = 'Metrics' 
df = read_excel('sentence.xlsx', sheet_name = my_sheet_name)
df['.']=df['Sentence'].str.contains('.')
# df['VERB']=df['Sentence'].str.contains('.')
writer = pd.ExcelWriter('sentence.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Metrics')
writer.save()

预期结果:

Sentence                            Verb
I will go to the mall               True
the mall                            False
I may be here tomorrow.             True  

最佳答案

您可以使用 NLTK 来完成此操作,如下所示:

import nltk
import pandas as pd

df = pd.DataFrame({'sent': ['I will go to the mall', 'the mall', 'I may be here tomorrow.']})

def tag_verb(sent):
    words = nltk.word_tokenize(sent)
    tags = nltk.pos_tag(words)
    for t in tags:
        if t[1] == 'VB':
            return True
    return False

df['verb'] = df['sent'].apply(lambda x: tag_verb(x))

输出:

    sent                       verb
0   I will go to the mall      True
1   the mall                   False
2   I may be here tomorrow.    True

关于regex - 如何使用 spacy 和 pandas 检查动词是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324004/

相关文章:

Python:在文本中查找单词列表的最佳/有效方法?

python - 使用另一个 DataFrame 创建或修改 DataFrame

python - 如何通过网状结构在R中使用pandas编写csv?

python-3.x - 导入 'PunktWordTokenizer' 时出错

python - NLTK - 如何找出从 python 中安装的语料库?

c# - Linq (EntityFramework) 中的正则表达式,数据库中的字符串处理

regex - 使用正则表达式匹配utf-8编码中的任何中文字符

python - Pandas 高效 VWAP 计算

python - Python 中 NLTK 工具包的默认分块器是什么?

python - 在 url 调度中存储 bool 变量