2016-11-25 43 views
0

我是學習NLP的初學者。我讀了關於CFG的內容,我想將其應用於自頂向下的分析和自下而上的分析。我從頭到尾解析。我想用nltk和python 36繪製自頂向下的解析樹。我寫了下面的代碼,但它不起作用。什麼是錯的?有沒有人可以幫助我增強代碼?CFG自頂向下解析與Python的nltk 36

import nltk 
from nltk.tag import pos_tag 
from nltk.tokenize import word_tokenize 
from nltk.tree import * 
from nltk.draw import tree 
from nltk import Nonterminal, nonterminals, Production, CFG 
from nltk.parse import RecursiveDescentParser 
text = input('Please enter a sentence: ') 
words = text.split() 
sentence = pos_tag(words) 

grammar1 = nltk.CFG.fromstring(""" 
    S -> NP VP 
    S -> VP 
    VP -> V NP | V NP PP 
    NP -> Det N | Det N PP 
    PP -> P NP 
    V -> "saw" | "ate" | "walked" | "book" | "prefer" | "sleeps" 
    Det -> "a" | "an" | "the" | "my" | "that" 
    N -> "man" | "dog" | "cat" | "telescope" | "park" | "flight" | "apple" 
    P -> "in" | "on" | "by" | "with" 
    """) 

rd = nltk.RecursiveDescentParser(grammar1, "Input") 
result = rd.parse(sentence) 
result.draw() 

我輸入了這段文字來解析「book that flight」。

回答

0

下次您提出問題時,請不要只說「它不起作用」。解釋它失敗的地方以及發生了什麼(包括堆棧跟蹤和錯誤消息,如果失敗並出現錯誤)。

您的代碼有兩個問題:參數"Input"不屬於解析器構造函數。我不知道你從哪裏得到它,但要擺脫它。其次,CFG語法做他們自己的POS標記。將明文單詞列表words傳遞給解析器。

rd = nltk.RecursiveDescentParser(grammar1) 
result = rd.parse(words)