我想使用NLTK或其他最适合的库创建一个Python脚本,以正确识别给定的句子是否为疑问句(问题)。我尝试过使用正则表达式,但有些更复杂的情况正则表达式无法处理。因此,我想使用自然语言处理技术,有人能帮我吗?
回答:
这个可能会解决你的问题。
这里是代码:
import nltknltk.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 featuresfeaturesets = [(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))
这应该会输出类似0.67的数值,这是一个不错的准确率。如果你想通过这个分类器处理一段文本,可以尝试:
print(classifier.classify(dialogue_act_features(line)))
这样你就可以将字符串分类为是ynQuestion(是非问句)、Statement(陈述句)等,并提取你需要的信息。
这种方法使用了NaiveBayes(朴素贝叶斯),在我看来这是最简单的方法,当然还有许多其他处理这种问题的途径。希望这对你有帮助!