Python nltk:来自产品的语法

Python nltk:来自产品的语法,python,parsing,nltk,Python,Parsing,Nltk,展示了如何从树到产品,现在我只需要知道如何从产品到语法 def trees2productions(trees): """ Transform list of Trees to a list of productions """ productions = [] for t in trees: productions += t.productions() return productions 显示如何从预定义语法获取语法的结果,但不说明如何从结果转到语法。有人知道我是怎么做到的吗 &g

展示了如何从树到产品,现在我只需要知道如何从产品到语法

def trees2productions(trees):
""" Transform list of Trees to a list of productions """
productions = []
for t in trees:
    productions += t.productions()
return productions
显示如何从预定义语法获取语法的结果,但不说明如何从结果转到语法。有人知道我是怎么做到的吗

>>> 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']
nltk导入CFG中的
>>
>>>语法=CFG.fromstring(“”)
…S->NP VP
…PP->P NP
…NP->Det N | NP PP
…VP->V NP | VP PP
…Det->“a”|“the”
…N->“狗”|“猫”
…V->“追逐”|“sat”
…P->“on”|“in”
... """)
>>>文法
>>>grammar.start()
s
>>>grammar.productions()#doctest:+规范化_空格
[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']

我发现了如何按照代码解决问题,并对代码进行了一些更新。这是:

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)

也可以使用nltk从产品中诱导PCFG。诱导\u PCFG(非终端('S'),产品)