繁体   English   中英

如何打印文本的主题

[英]How can I print the subject of a text

我使用此代码来确定主题,句子的时间/位置。

from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
import nltk

text = input('Please enter a sentence: ')
words = text.split()
sentence = pos_tag(words)

grammar = '''
Action: {<NN.*>?<VB.*><RB.*>?}
Location: {<IN><NN.*>+}
Subject: {<DT>?<JJ>*<NN.*>}
'''
cp = nltk.RegexpParser(grammar, "Input")
result = cp.parse(sentence)

result.draw()

我如何只打印句子的主题?

您可以使用Tree对象的“标签”属性。 在这里,我设置了一个循环来检查结果的每个元素,以查看它是否是nltk.tree.Tree实例。 然后,如果标签为“主题”,则将其附加到

subject = []
for word in result:
    print word
    if isinstance(word, nltk.tree.Tree):
        if word.label() == 'Subject':
            subject.append(word)

# Sentence returned multiple subjects, including direct object, so draw first one
subject[0].draw()

当然,这假设您要绘制的是标有“主题”的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM