Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中验证表达式/中缀_Python_Expression_Infix Notation_Arithmetic Expressions - Fatal编程技术网

在python中验证表达式/中缀

在python中验证表达式/中缀,python,expression,infix-notation,arithmetic-expressions,Python,Expression,Infix Notation,Arithmetic Expressions,如何在python中验证表达式/中缀?可能吗? 例如: a-d*9 5-(a*0.3-d+(0.4-e))/k*5 (a-d*9)/(k-y-4.3*e)+(t-7*c) 如果需要Python风格的表达式,可以在ast模块中使用解析器,并检查SyntaxError: >>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5') <_ast.Module object at 0x7fc7bdd9e790> >>> ast.par

如何在python中验证表达式/中缀?可能吗? 例如:

a-d*9
5-(a*0.3-d+(0.4-e))/k*5
(a-d*9)/(k-y-4.3*e)+(t-7*c)

如果需要Python风格的表达式,可以在
ast
模块中使用解析器,并检查
SyntaxError

>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5')
<_ast.Module object at 0x7fc7bdd9e790>
>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    5-(a*0.3-d+(0.4-e))/k*
                        ^
SyntaxError: unexpected EOF while parsing
ast.parse('5-(a*0.3-d+(0.4-e))/k*5') >>>ast.parse('5-(a*0.3-d+(0.4-e))/k*')) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“/usr/lib/python2.6/ast.py”,第37行,在parse中 返回编译(expr、文件名、模式、仅PyCF\u AST) 文件“”,第1行 5-(a*0.3-d+(0.4-e))/k* ^ SyntaxError:分析时出现意外的EOF 虽然这可能比您实际需要的要多得多:

>>> ast.parse('def spam(): return "ham"')
<_ast.Module object at 0x7fc7bdd9e790>
ast.parse('def spam():返回“ham”)
因此,您可能需要仔细检查返回的解析树。

答案很简单:创建一个解析器。你能展示一下到目前为止你都做了些什么吗?你有什么特别的问题吗?我创建了一个解析器。在执行之前。我需要一个验证程序来验证它。@Zeck:解析器通过解析失败来验证表达式。如果解析器未能完成,则表达式无效。在解析之前不进行验证。验证是解析的结果。如果解析器完成,则它是有效的。如果解析器失败,那么它是无效的。不要“预先验证”。那是错误的。