This link展示了如何从树木到制作,现在我只需要知道如何从制作到语法。
def trees2productions(trees):
""" Transform list of Trees to a list of productions """
productions = []
for t in trees:
productions += t.productions()
return productions
This page展示了如何从预定义的语法中获得语法的制作,但它没有说明如何从制作到语法。有谁知道我怎么能这样做?
>>> 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']
答案 0 :(得分:1)
我已经找到了如何在代码here之后解决我的问题并稍微更新一下。这是:
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)