Python-NLTK:使用联合结构解析字符串,进入无限递归

2024-04-26 00:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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'|...

谢谢你。你知道吗


Tags: andtheparserstringrdsentencedognltk
1条回答
网友
1楼 · 发布于 2024-04-26 00:32:41

您可能想定义这样的内容(顺便说一句,这有点非常规):

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”。我不能保证这将只生成有意义的句子,但它应该允许解析器终止。你知道吗

相关问题 更多 >