あなたは括弧解析されたからルールを作成するために探しているなら、あなたはTree.productions()
01を使用することができます
>>> 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']
Tree.productions()
がnltk.grammar.Productions
オブジェクトのリストを返します:Production.unicode_repr
を使用して、文字列形式にルールを取得するには
>>> type(t.productions()[0])
<class 'nltk.grammar.Production'>
を:
>>> t.productions()[0].unicode_repr()
u'S -> NP VP'
の取得文字列表現に括弧で括られた文法から学んだ文法:
>>> 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'
あなたの質問を編集して、必要なことをより明確にしてください。最初の文章ではカッコで囲まれた書式が必要であると言います.2番目の文章では、この文のために発した基礎文法の部分を出力します。 – lenz
"fromstring"の代わりに一貫して "formstring"と入力すると、多少の混乱が生じることがあります。探している形式は解析木ではなく、文法仕様です(出力ではなくパーサの入力の1つです)。だから私はすでにそれに自動的な解決策があるのか疑問だ。 – lenz
はい私は混乱を修正しました。それはfromstringです。私はそれが入力として使われる文法仕様だと理解しています。解析木を指定すると、このような仕様を作成することはできますか?それは私に時間と労力を節約します。 NLTKだけでなく、他の方法でも。そのような既製の解決策が存在しない場合、それを作成することは可能ですか? –