<p>如果要从括号中解析创建规则,可以使用<a href="http://www.nltk.org/api/nltk.html#nltk.tree.Tree.productions" rel="nofollow">^{<cd1>}</a></p>
<pre><code>>>> from nltk import Tree
>>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
>>> t.productions()
[S -> NP VP, NP -> D N, D -> 'the', N -> 'dog', VP -> V NP, V -> 'chased', NP -> D N, D -> 'the', N -> 'cat']
</code></pre>
<p><code>Tree.productions()</code>将返回<a href="https://github.com/nltk/nltk/blob/develop/nltk/grammar.py#L236" rel="nofollow">^{<cd3>}</a>对象的列表:</p>
^{pr2}$
<p>要将规则转换为字符串形式,请使用<code>Production.unicode_repr</code>:</p>
<pre><code>>>> t.productions()[0].unicode_repr()
u'S -> NP VP'
</code></pre>
<p>要获得括号内语法的字符串表示,请执行以下操作:</p>
<pre><code>>>> from nltk import Tree
>>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
>>> grammar_from_parse = "\n".join([rule.unicode_repr() for rule in t.productions()])
>>> print grammar_from_parse
S -> NP VP
NP -> D N
D -> 'the'
N -> 'dog'
VP -> V NP
V -> 'chased'
NP -> D N
D -> 'the'
N -> 'cat'
</code></pre>