我正在尝试使用 NLTK检查给定的句子是否符合语法。
前任:
OK : 鲸舔悲伤
不好:我曾经拥有过的最好的
我知道我可以进行 POS 标记,然后使用 CFG 解析器并以这种方式进行检查,但我还没有找到使用 POS 标记而不是实际单词作为终端分支的 CFG。
有没有人可以推荐的CFG?我认为自己制作是愚蠢的,因为我不是语言学家,可能会遗漏重要的结构。
另外,我的应用程序是这样的,理想情况下,系统会拒绝许多句子,只批准它非常确定的句子。
感谢:D
CFG 的终端节点可以是任何东西,甚至是 POS 标签。只要您的短语规则将 POS 而不是单词识别为输入,使用 POS 声明语法应该没有问题。
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