我是学习 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
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()
我输入此文本以解析“预订该航班”。