【问题标题】:Python NLTK: parse string using conjoint structure, getting into infinite recursionPython NLTK:使用联合结构解析字符串,进入无限递归
【发布时间】:2016-01-09 04:45:27
【问题描述】:

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

谢谢。

【问题讨论】:

  • 我认为,如果你这样描述你的语法,解析器就无法区分原语和短语

标签: python recursion stack-overflow nltk


【解决方案1】:

你可能想定义这样的东西(顺便说一句,这有点非传统):

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'。我不保证这只会生成有意义的句子,但它应该允许解析器终止。

【讨论】:

  • 感谢您的帮助。但它并没有终止,我得到了同样的错误
  • 哎呀,我有一个错误,已修复。不是“WF”而是“WF”
猜你喜欢
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
相关资源
最近更新 更多