How to parse a sentence using grammars provided by nltk?

Sohail nawabadeel at gmail.com
Thu Aug 12 11:56:27 EDT 2010


Hi,

When I define my own production rules for the grammar the code below
runs fine. Can anyone tell me how to use the built in grammars of nltk
(if there are any)?

>>> groucho_grammar = nltk.parse_cfg("""
... S -> NP VP
... PP -> P NP
... NP -> Det N | Det N PP | 'I'
... VP -> V NP | VP PP
... Det -> 'an' | 'my'
... N -> 'elephant' | 'pajamas'
... V -> 'shot'
... P -> 'in'
... """)
>>> sent = ['I', 'shot', 'an', 'elephant', 'in', 'my', 'pajamas']
>>> parser = nltk.ChartParser(groucho_grammar)
>>> trees = parser.nbest_parse(sent)
>>> for tree in trees:
...     print tree

thanks



More information about the Python-list mailing list