使用Shift Reduce解析器的上下文无关语法

时间:2018-12-10 14:34:23

标签: python parsing context-free-grammar shift-reduce

我正在尝试将Shift Reduce解析器用于以下句子:

He eats pasta with some anchovies in the restaurant

我已经创建了一些代码和语法,但是语法只能在以下情况下起作用:

He eats pasta with some anchovies

import nltk
from nltk.parse import ShiftReduceParser


grammar = nltk.CFG.fromstring("""

S -> NP VP
NP -> PropN | N PP | Det N
VP -> V NP | V S | VP PP | NP PP
PP -> P NP 
PropN -> 'He'
Det -> 'some' | 'the'
N -> 'pasta' | 'anchovies' | 'restaurant'
V -> 'eats'
P -> 'with' | 'in'

""")


sr = ShiftReduceParser(grammar)

sentence1 = 'He eats pasta with some anchovies'
# He eats pasta with some anchovies in the restaurant

tokens = nltk.word_tokenize(sentence1)



print("--------------------------- Sentence 1 ---------------------------")

for x in sr.parse(tokens):
    print(x)

现在我尝试将Det NP添加到NP -> this other question on the topic

但是显然Det NP是不正确的语法。我的错误是在哪个区域,我将如何使移位解析器完全解析我的句子。

0 个答案:

没有答案