簡體   English   中英

nltk:作品語法

[英]nltk: Grammar from productions

此鏈接顯示了如何從樹到生成詞,現在我只需要知道如何從生成詞到語法。

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']

這里的代碼之后,我發現了如何解決我的問題並對其進行了一些更新。 這里是:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM