Reputation: 277
This link shows how it's possible to go from trees to productions, now I would just need to know how to go from the productions to a grammar.
def trees2productions(trees):
""" Transform list of Trees to a list of productions """
productions = []
for t in trees:
productions += t.productions()
return productions
This page shows how to get a grammar's productions from a pre-defined grammar but it does not tell how to go from the productions to the grammar. Does anyone know how I could do that?
>>> from nltk import CFG
>>> grammar = CFG.fromstring("""
... S -> NP VP
... PP -> P NP
... NP -> Det N | NP PP
... VP -> V NP | VP PP
... Det -> 'a' | 'the'
... N -> 'dog' | 'cat'
... V -> 'chased' | 'sat'
... P -> 'on' | 'in'
... """)
>>> grammar
<Grammar with 14 productions>
>>> grammar.start()
S
>>> grammar.productions() # doctest: +NORMALIZE_WHITESPACE
[S -> NP VP, PP -> P NP, NP -> Det N, NP -> NP PP, VP -> V NP, VP -> VP PP,
Det -> 'a', Det -> 'the', N -> 'dog', N -> 'cat', V -> 'chased', V -> 'sat',
P -> 'on', P -> 'in']
Upvotes: 1
Views: 2079
Reputation: 277
I have found how to solve my problem following the code here and updating it a little. Here it is:
import nltk
from nltk.grammar import CFG, Nonterminal
productions = [S -> NP VP, PP -> P NP, NP -> Det N, NP -> NP PP, VP -> V NP, VP -> VP PP, Det -> 'a', Det -> 'the', N -> 'dog', N -> 'cat', V -> 'chased', V -> 'sat', P -> 'on', P -> 'in']
grammar = CFG(Nonterminal('S'), productions)
Upvotes: 1