如何在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)发布于 2011-07-19 16:46:00
如果需要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('def spam(): return "ham"')
<_ast.Module object at 0x7fc7bdd9e790>因此,您可能需要仔细检查返回的解析树。
https://stackoverflow.com/questions/6744389
复制相似问题