【问题标题】:checking action in a sentence检查动作造句
【发布时间】:2016-05-09 02:34:46
【问题描述】:

现在我已经确定了使用此代码的主题、动作和位置/时间:

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

text = input('Please enter a sentence: ')
words = text.split()
sent = [w for w in words if not w == 'computer']
sentence = pos_tag(sent)

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

subjects = []
actions = []
locations_times = []

for word in result:
    if isinstance(word, nltk.tree.Tree):
        if word.label() == 'Subject':
            subjects.append(word)

for word in result:
    if isinstance(word, nltk.tree.Tree):
        if word.label() == 'Action':
            actions.append(word)

for word in result:
    if isinstance(word, nltk.tree.Tree):
        if word.label() == 'Location/Time':
            locations_times.append(word)

我如何检查操作 == 'whatever' 是否执行某项操作,否则执行其他操作。

我在输入“现在是什么时间”时尝试过这个,但它总是打印失败:

if actions[0] == '(Action time/NN is/VBZ)':
    print('success')
else:
    print('failure')

请帮忙

【问题讨论】:

  • 你输入了什么?

标签: python python-3.x nltk


【解决方案1】:

解析器的结果将至少是一个Tree 对象,您必须对其进行递归评估。有关使用解析器及其返回结果的示例,请参阅 this answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2021-04-17
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多