nltk CFG,定义语法规则 [英] nltk CFG, defining grammar rules

查看:88
本文介绍了nltk CFG,定义语法规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已编辑,我需要解析以下句子:列出飞往丹佛的航班的座位".下面的代码应该工作,但不能.问题出在nltk.CFG.fromstring命令中,我敢肯定其他功能也能正常工作.有什么想法可以在这里正确定义语法规则吗?

EDITED I need to parse the following sentence: "List me the seats on the flight to Denver". The code below SHOULD work, but doesn't. The problem lies within the nltk.CFG.fromstring command, i am sure the other functions work. Any ideas how to properly define the grammar rules here?

import nltk
from nltk.corpus import treebank



# here we define a grammar


import nltk
from nltk.corpus import treebank

grammar = nltk.CFG.fromstring("""

S -> NP VP | VP |IVP

IVP -> IV NP NP PP | IV NP NP

NP -> NNS | Det Nom | 'Denver'

Nom -> Nom N | Nom PP | N

VP -> V NP PP | V PP  | V NP | V | TO VP

PP -> IN NP | PRP NP


Det ->'the'
IN -> 'on'
TO -> 'to'
PRP ->'me'
N ->'flight'
NNS -> 'seats'
V ->  'List'
 """)



# here we let nltk construct a chart parser from our grammar
parser = nltk.ChartParser(grammar)

# input: a list of words
# returns all the parses of a sentence
def allParses(sentenceList):
    return parser.parse(sentenceList)

# input: a list of parse trees
# prints all the parse trees
def printParses(parses):
    for tree in parses:
        print(tree)

# input: a sentence as a string or as a list of words
# prints a sentence, then parses it and prints all the parse trees
def processSentence(sentence):
    sentenceList = sentence
    if isinstance(sentence,str):
        sentenceList = sentence.split(' ')
    print('Original sentence: ' + ' '.join(sentenceList))
    printParses(allParses(sentenceList))

def mainScript():
    processSentence('List me the seats on the flight to Denver')

感谢您的帮助.

推荐答案

列表"也可以是名词:N->'列表'
也许还会在箭头和单词之间留出空格:
N->'航班'应该为N->'航班'|列表"
座位"也可以是动词.例如:她就座"或他就座"
规则也不完整.例如,对于IV-> ??

"List" can be also a noun: N -> 'List'
Maybe also put space between the arrow and the word:
N ->'flight' should be N -> 'flight' | 'List'
"seats" can also be a verb. For example: "She seats" or "He seats"
Also the rules are not complete. For example there is no rule for IV -> ??

这篇关于nltk CFG,定义语法规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆