2

我正在尝试将 Shift Reduce Parser 用于以下句子:

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 NPNP -> 在此处输入图像描述

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

4

0 回答 0