from coursepy.lang.parsing import make_parser, make_cfg

grammar_text = """
S  -> NP VP
NP -> Det N | Det N PP
VP -> V NP | VP PP
PP -> P NP
Det -> 'the' | 'a'
N  -> 'dog' | 'owner' | 'leash'
V  -> 'found'
P  -> 'with'
"""

parse = make_parser(make_cfg(grammar_text))

[t.pretty_print() for t in parse("the owner found the dog with the leash")]
                     S                            
      _______________|_______                      
     |                       VP                   
     |                _______|________             
     |               VP               PP          
     |           ____|___         ____|___         
     NP         |        NP      |        NP      
  ___|____      |     ___|___    |     ___|____    
Det       N     V   Det      N   P   Det       N  
 |        |     |    |       |   |    |        |   
the     owner found the     dog with the     leash

                     S                        
      _______________|___                      
     |                   VP                   
     |           ________|___                  
     |          |            NP               
     |          |     _______|____             
     |          |    |   |        PP          
     |          |    |   |    ____|___         
     NP         |    |   |   |        NP      
  ___|____      |    |   |   |     ___|____    
Det       N     V   Det  N   P   Det       N  
 |        |     |    |   |   |    |        |   
the     owner found the dog with the     leash
[None, None]

Download .ipynb Download .py