如何使用spacy和pandas检查动词的存在?

问题描述 投票:1回答:1
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  
regex pandas nltk spacy
1个回答
2
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.