简体   繁体   中英

Python NLTK: parse string using conjoint structure, getting into infinite recursion

I am new in python and nltk. I am asked to create two different parse tree for the following sentence:

Adam slept while Josh ate and the dog barked. 

Based on these two constructions:

S-> S while S
S-> S and S

Here is what I wrote so far, I used this page (4.1) as a guideline.

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)

This code doesn't work. I am getting this error:

    if isinstance(index, (int, slice)):
RuntimeError: maximum recursion depth exceeded in __instancecheck__

I am wondering what is wrong with my code? Is it because of this: S -> 'Adam'|'slept'|'Josh'|...

Thank you.

You probably want to define something like this (which is somewhat non-conventional, by the way):

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' stays for 'fragment' here. I don't guarantee that this would generate only meaningful sentences, but it should hopefully allow the parser to terminate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM