如何检查句子是否正确(Python中的简单语法检查)? [英] How to check whether a sentence is correct (simple grammar check in Python)?

查看:208
本文介绍了如何检查句子是否正确(Python中的简单语法检查)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查句子在Python中是否有效?

示例:

I love Stackoverflow - Correct
I Stackoverflow love - Incorrect

解决方案

查看 NLTK .他们支持语法,您可以使用语法来分析句子.您可以定义语法,也可以使用提供的语法以及无上下文的解析器.如果句子解析,则它具有有效的语法;如果没有,那就没有.这些语法可能没有最广泛的覆盖范围(例如,它可能不知道如何处理StackOverflow之类的单词),但是这种方法可以让您明确说明语法中什么是有效的还是无效的. NLTK书的第8章涵盖了解析过程,并应解释您需要了解的内容.

一种替代方法是为覆盖面广的解析器编写python接口(例如斯坦福解析器 C& C ).这些是统计解析器,即使他们以前没有看过所有单词或语法结构,也能够理解句子.缺点是有时语法分析器仍会返回语法错误的句子的语法分析,因为它将使用统计信息来进行最佳猜测.

因此,这实际上取决于您的目标是什么.如果要非常精确地控制被认为是语法的内容,请对NLTK使用上下文无关的解析器.如果需要鲁棒性和广泛的覆盖范围,请使用统计分析器.

How to check whether a sentence is valid in Python?

Examples:

I love Stackoverflow - Correct
I Stackoverflow love - Incorrect

解决方案

Check out NLTK. They have support for grammars that you can use to parse your sentence. You can define a grammar, or use one that is provided, along with a context-free parser. If the sentence parses, then it has valid grammar; if not, then it doesn't. These grammars may not have the widest coverage (eg, it might not know how to handle a word like StackOverflow), but this approach will allow you to say specifically what is valid or invalid in the grammar. Chapter 8 of the NLTK book covers parsing and should explain what you need to know.

An alternative would be to write a python interface to a wide-coverage parser (like the Stanford parser or C&C). These are statistical parsers that will be able to understand sentences even if they haven't seen all the words or all the grammatical constructions before. The downside is that sometimes the parser will still return a parse for a sentence with bad grammar because it will use the statistics to make the best guess possible.

So, it really depends on exactly what your goal is. If you want very precise control over what is considered grammatical, use a context-free parser with NLTK. If you want robustness and wide-coverage, use a statistical parser.

这篇关于如何检查句子是否正确(Python中的简单语法检查)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆