N-6ren">
gpt4 book ai didi

python-2.7 - Python 和 NLTK : How to analyze sentence grammar?

转载 作者:行者123 更新时间:2023-12-04 01:04:55 24 4
gpt4 key购买 nike

我有这段代码,它应该根据定义的语法显示句子的句法结构。但是它返回一个空的[]。我错过了什么或做错了什么?

import nltk

grammar = nltk.parse_cfg("""
S -> NP VP
PP -> P NP
NP -> Det N | Det N PP
VP -> V NP | VP PP
N -> 'Kim' | 'Dana' | 'everyone'
V -> 'arrived' | 'left' |'cheered'
P -> 'or' | 'and'
""")

def main():
sent = "Kim arrived or Dana left and everyone cheered".split()
parser = nltk.ChartParser(grammar)
trees = parser.nbest_parse(sent)
for tree in trees:
print tree

if __name__ == '__main__':
main()

最佳答案

您没有 Det在您的语法中定义,但每个 NP (因此 S )必须有一个语法定义。

与之比较

>>> grammar = nltk.parse_cfg("""
... S -> NP VP
... NP -> Det N | Det N PP
... VP -> V NP | VP PP
... Det -> 'a' | 'the'
... N -> 'Kim' | 'Dana' | 'everyone'
... V -> 'arrived' | 'left' |'cheered'
... """)
>>>
>>> parser = nltk.ChartParser(grammar)
>>> parser.nbest_parse('the Kim left a Dana'.split())
[Tree('S', [Tree('NP', [Tree('Det', ['the']), Tree('N', ['Kim'])]), Tree('VP', [Tree('V', ['left']), Tree('NP', [Tree('Det', ['a']), Tree('N', ['Dana'])])])])]

关于python-2.7 - Python 和 NLTK : How to analyze sentence grammar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com