为nltk解析树生成语法规则 [英] generating grammar rules for nltk parse trees
本文介绍了为nltk解析树生成语法规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有句子"Mary saw a dog"
和以下内容:
If I have the sentence "Mary saw a dog"
and the following:
pos_tags = ['NNP', 'VBD', 'DT', 'NN']
是否可以为此句子生成语法规则,以便生成解析树(下面的语法是使用nltk.parse_cfg
的语法规则)
Is it possible to generate the grammar rules for this sentence so that a parse tree can be generated (grammar below are the grammar rules using nltk.parse_cfg
)
sent = "Mary saw a dog".split()
rd_parser = nltk.RecursiveDescentParser(grammar)
for tree in rd_parser.nbest_parse(sent):
print tree
推荐答案
您可以尝试:
import nltk
# Define the cfg grammar.
grammar = nltk.parse_cfg("""
S -> NP VP
NP -> 'DT' 'NN'
VP -> 'VB'
VP -> 'VB' 'NN'
""")
# Make your POS sentence into a list of tokens.
sentence = "DT NN VB NN".split(" ")
# Load the grammar into the ChartParser.
cp = nltk.ChartParser(grammar)
# Generate and print the nbest_parse from the grammar given the sentence tokens.
for tree in cp.nbest_parse(sentence):
print tree
但是正如@alexis强调的那样,您要的是几乎不可能的=)
But as @alexis highlighted, what you're asking for it rather impossible =)
这篇关于为nltk解析树生成语法规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文