簡體   English   中英

使用python 36在nltk中進行CFG自上而下的解析

[英]CFG top down parsing in nltk with python 36

我是學習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()

我輸入此文本用於解析“預訂該航班”。

下次您問一個問題時,不要只說“它不起作用”。 解釋失敗的地方和發生的情況(包括堆棧跟蹤和錯誤消息,如果失敗並顯示錯誤)。

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

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

暫無
暫無

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

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