Python 如何打印文本的主题

Python 如何打印文本的主题,python,python-3.x,nltk,Python,Python 3.x,Nltk,我用这个代码来确定一个句子的主语和时间/位置 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.

我用这个代码来确定一个句子的主语和时间/位置

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()
从nltk.tag导入pos_标签
从nltk.tokenize导入单词\u tokenize
导入nltk
text=输入('请输入一个句子:')
words=text.split()
句子=位置标记(单词)
语法='''
操作:{???}
位置:{+}
主题:{?*}
'''
cp=nltk.RegexpParser(语法,“输入”)
结果=cp.parse(句子)
结果.draw()
如何仅打印句子的主题?

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

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()
当然,这假设任何标记为“主题”的东西都是您想要绘制的