使用python 36在nltk中进行CFG自顶向下解析
我是学习NLP的初学者。我读过关于CFG的文章,我想将其应用于自顶向下的解析和自底向上的解析。我从自顶向下的解析开始。我想用nltk和python 36绘制自顶向下的解析树。我编写了以下代码,但它不起作用。怎么了?有人能帮我增强代码吗使用python 36在nltk中进行CFG自顶向下解析,python,python-3.x,nltk,text-parsing,topdown,Python,Python 3.x,Nltk,Text Parsing,Topdown,我是学习NLP的初学者。我读过关于CFG的文章,我想将其应用于自顶向下的解析和自底向上的解析。我从自顶向下的解析开始。我想用nltk和python 36绘制自顶向下的解析树。我编写了以下代码,但它不起作用。怎么了?有人能帮我增强代码吗 import nltk from nltk.tag import pos_tag from nltk.tokenize import word_tokenize from nltk.tree import * from nltk.draw import tree
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()
我输入这段文字是为了解析“预订那次航班”。下次你问问题时,不要只说“它不起作用”。解释它在哪里失败以及发生了什么(包括堆栈跟踪和错误消息,如果它因错误而失败) 代码有两个问题:参数
“Input”
不属于解析器构造函数。我不知道你是从哪里弄来的,但是把它扔掉。其次,CFG语法有自己的词性标注。将普通单词列表单词传递给解析器
rd = nltk.RecursiveDescentParser(grammar1)
result = rd.parse(words)
下次你问问题时,不要只说“它不起作用”。解释它在哪里失败以及发生了什么(包括堆栈跟踪和错误消息,如果它因错误而失败)
代码有两个问题:参数“Input”
不属于解析器构造函数。我不知道你是从哪里弄来的,但是把它扔掉。其次,CFG语法有自己的词性标注。将普通单词列表单词传递给解析器
rd = nltk.RecursiveDescentParser(grammar1)
result = rd.parse(words)