Python NLTK: parse string using conjoint structure, getting into infinite recursion
Question: 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)](http://www.nltk.org/book/ch08.html) 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.


Answer: 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.

