2016-11-25 67 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)