Python NLTK:使用联合结构解析字符串,进入无限递归
Python NLTK: parse string using conjoint structure, getting into infinite recursion
我是 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' 在这里停留 'fragment'。我不保证这只会生成有意义的句子,但它应该允许解析器终止。
我是 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' 在这里停留 'fragment'。我不保证这只会生成有意义的句子,但它应该允许解析器终止。