NLTK。检测一个句子是否为疑问句?

Fre*_*ant 6 python nlp artificial-intelligence machine-learning nltk

我想使用 NLTK 或任何最能正确识别给定句子是否为疑问句(问题)的库创建一个 python 脚本。我尝试使用正则表达式,但在更深层次的情况下正则表达式失败。所以想使用自然语言处理任何人都可以帮忙!

Pol*_*Dot 12

可能会解决您的问题。

这是代码:

import nltk
nltk.download('nps_chat')
posts = nltk.corpus.nps_chat.xml_posts()[:10000]


def dialogue_act_features(post):
    features = {}
    for word in nltk.word_tokenize(post):
        features['contains({})'.format(word.lower())] = True
    return features

featuresets = [(dialogue_act_features(post.text), post.get('class')) for post in posts]
size = int(len(featuresets) * 0.1)
train_set, test_set = featuresets[size:], featuresets[:size]
classifier = nltk.NaiveBayesClassifier.train(train_set)
print(nltk.classify.accuracy(classifier, test_set))
Run Code Online (Sandbox Code Playgroud)

这应该打印出类似 0.67 的东西,这是一个不错的准确度。如果要通过此分类器处理文本字符串,请尝试:

print(classifier.classify(dialogue_act_features(line)))
Run Code Online (Sandbox Code Playgroud)

并且您可以将字符串分类为是否是 ynQuestion、Statement 等,并提取您想要的内容。

这种方法是使用 NaiveBayes,在我看来这是最简单的,但是肯定有很多方法可以处理这个问题。希望这可以帮助!