This link展示了如何从树到产生式,现在我只需要知道如何从产生式到文法。
def trees2productions(trees):
""" Transform list of Trees to a list of productions """
productions = []
for t in trees:
productions += t.productions()
return productionsThis 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']发布于 2016-01-20 01:27:34
我已经找到了如何按照代码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)https://stackoverflow.com/questions/34882246
复制相似问题