用python编写的数学语法检查器 [英] math syntax checker written in python
问题描述
我需要做的就是使用python检查字符串是否是有效的数学表达式.
All I need is to check, using python, if a string is a valid math expression or not.
为简单起见,假设我只需要带有数字和嵌套括号的+ - * /
运算符(也为+ -
一元).为了完整起见,我还添加了简单的变量名称.
For simplicity let's say I just need + - * /
operators (+ -
as unary too) with numbers and nested parenthesis. I add also simple variable names for completeness.
所以我可以这样测试:
test("-3 * (2 + 1)") #valid
test("-3 * ") #NOT valid
test("v1 + v2") #valid
test("v2 - 2v") #NOT valid ("2v" not a valid variable name)
我尝试了 pyparsing ,但是仅尝试了示例:我总是在不引发异常的情况下解析错误的语法
I tried pyparsing but just trying the example: "simple algebraic expression parser, that performs +,-,*,/
and ^
arithmetic operations" I get passed invalid code and also trying to fix it I always get wrong syntaxes being parsed without raising Exceptions
只需尝试:
>>>test('9', 9)
9 qwerty = 9.0 ['9'] => ['9']
>>>test('9 qwerty', 9)
9 qwerty = 9.0 ['9'] => ['9']
都通过测试... o_O
both test pass... o_O
有什么建议吗?
推荐答案
这是因为pyparsing代码允许使用函数.(顺便说一句,它的功能远远超出了您的需求,即创建一个堆栈并对其进行评估.)
This is because the pyparsing code allows functions. (And by the way, it does a lot more than what you need, i.e. create a stack and evaluate that.)
对于初学者来说,您可以从代码中删除 pi
和ident
(可能还有我现在缺少的其他东西)以禁止字符.
For starters, you could remove pi
and ident
(and possibly something else I'm missing right now) from the code to disallow characters.
原因不同:默认情况下,PyParsing解析器不会尝试使用整个输入.您必须在expr
的末尾添加+ StringEnd()
(当然是将其导入),以使其在无法解析整个输入的情况下失败.在这种情况下,pyparsing.ParseException
将被引发. (来源: http://pyparsing-public.wikispaces.com/FAQs )
The reason is different: PyParsing parsers won't try to consume the whole input by default. You have to add + StringEnd()
(and import it, of course) to the end of expr
to make it fail if it can't parse the whole input. In that case, pyparsing.ParseException
will be raised. (Source: http://pyparsing-public.wikispaces.com/FAQs)
如果您想学习一些解析,则可以使用任何不错的解析库在不到三十行的内容中构建所需的内容(我喜欢
If you care to learn a bit of parsing, what you need can propably be built in less than thirty lines with any decent parsing library (I like LEPL).
这篇关于用python编写的数学语法检查器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!