nltk: Grammar from productions
<p><a href="http://tech.swamps.io/training-a-simple-pcfg-parser-using-nltk/" rel="nofollow">This link</a> 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. </p>

<pre><code>def trees2productions(trees):
""" Transform list of Trees to a list of productions """
productions = []
for t in trees:
    productions += t.productions()
return productions
</code></pre>

<p><a href="http://www.nltk.org/howto/grammar.html" rel="nofollow">This page</a> 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? </p>

<pre><code>&gt;&gt;&gt; from nltk import CFG
&gt;&gt;&gt; grammar = CFG.fromstring("""
... S -&gt; NP VP
... PP -&gt; P NP
... NP -&gt; Det N | NP PP
... VP -&gt; V NP | VP PP
... Det -&gt; 'a' | 'the'
... N -&gt; 'dog' | 'cat'
... V -&gt; 'chased' | 'sat'
... P -&gt; 'on' | 'in'
... """)
&gt;&gt;&gt; grammar
&lt;Grammar with 14 productions&gt;
&gt;&gt;&gt; grammar.start()
S
&gt;&gt;&gt; grammar.productions() # doctest: +NORMALIZE_WHITESPACE
[S -&gt; NP VP, PP -&gt; P NP, NP -&gt; Det N, NP -&gt; NP PP, VP -&gt; V NP, VP -&gt; VP PP,
Det -&gt; 'a', Det -&gt; 'the', N -&gt; 'dog', N -&gt; 'cat', V -&gt; 'chased', V -&gt; 'sat',
P -&gt; 'on', P -&gt; 'in']
</code></pre>