我是 python 和 nltk 的新手。我被要求为以下句子创建两个不同的解析树:
Adam slept while Josh ate and the dog barked.
基于这两个结构:
S-> S while S
S-> S and S
这是我到目前为止写的,我使用了this page (4.1)作为指南。
import nltk
grammar_string = '''
S -> S 'and' S
S -> S 'or' S
S -> S 'but' S
S -> S 'while' S
S -> S 'when' S
S -> 'Adam'|'slept'|'Josh'|'ate'|'the'|'dog'|'barked'
'''
sentence = "Adam slept while Josh ate and the dog barked"
grammar = nltk.CFG.fromstring(grammar_string)
rd_parser = nltk.RecursiveDescentParser(grammar)
sent = sentence.split()
for tree in rd_parser.parse(sent):
print(tree)
此代码无效。我收到此错误:
if isinstance(index, (int, slice)):
RuntimeError: maximum recursion depth exceeded in __instancecheck__
我想知道我的代码有什么问题?是不是因为这个:S -> 'Adam'|'slept'|'Josh'|...
谢谢。
请您参考如下方法:
你可能想定义这样的东西(顺便说一下,这有点不合常规):
S -> P
P -> P u P | F
F -> W | W F
u -> 'and'| 'or' | 'but' | 'while' | 'when'
W -> 'Adam'|'slept'|'Josh'|'ate'|'the'|'dog'|'barked'
“F”在这里代表“片段”。我不保证这只会生成有意义的句子,但它应该允许解析器终止。
