regex - 如何使用 spacy 和 pandas 检查动词的存在?
问题描述
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
推荐阅读
- drupal-8 - 为什么 PhpSpreadsheet 无法在 public:// 中识别我的 Xlsx 文件?
- html - 在带有过渡的链接悬停时显示图像
- reactjs - 无法使用 firebase 在本地运行 mocha 测试
- graphql - HTML 结构的 GraphQL 自定义标量类型
- python - Flask 禁用 JSON 响应转义
- python - 如何在特定行上旋转熊猫数据框
- apache-kafka - Kafka Mirror Maker:同步 __consumer_offsets 主题重复项
- php - 如何在三个表上运行两个查询并在一个表中输出一列的结果
- python - 我的列表正在更改,我不知道为什么
- java - 向 arrayList 添加标记会导致应用程序崩溃