NLP:根据给定语法验证一个句子

2024-05-17 10:11:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个英语句子的语料库

sentences = [
    "Mary had a little lamb.",
    "John has a cute black pup.",
    "I ate five apples."
]

语法(为了简单起见)

grammar = ('''
    NP: {<NNP><VBZ|VBD><DT><JJ>*<NN><.>} # NP
    ''')

我想把不符合语法的句子过滤掉。 是否有一个内置的NLTK函数可以实现这一点? 在上面的例子中,前两句遵循我的语法模式,但不是最后一句。你知道吗


Tags: cutenp语法sentencesjohn句子blackhas
2条回答

TL;博士

写一个语法,检查它是否被解析,遍历子树,寻找你要寻找的非终端,例如NP

请参见:

代码:

import nltk

grammar = ('''
    NP: {<NNP><VBZ|VBD><DT><JJ>*<NN><.>} # NP
    ''')

sentences = [
    "Mary had a little lamb.",
    "John has a cute black pup.",
    "I ate five apples."
]

def has_noun_phrase(sentence):
    parsed = chunkParser.parse(pos_tag(word_tokenize(sentence)))
    for subtree in parsed:
        if type(subtree) == nltk.Tree and subtree.label() == 'NP':
            return True
    return False

chunkParser = nltk.RegexpParser(grammar)
for sentence in sentences:
    print(has_noun_phrase(sentence))

NLTK支持词性标注,您可以先对句子进行词性标注,然后与预定义的语法进行比较。下面是一个使用NLTK词性标注的示例。你知道吗

enter image description here

相关问题 更多 >