我正在尝试使用最终的子公式在python中开发一个方程式解析器。这个想法是用户可能会给出一个其变量并非全部已知的方程式。但是可能会为这些未定义的变量定义一些子公式。然后程序应该用子公式替换未知变量。使用@ebarr here提供的帮助,我进一步发展了这个想法,但由于一个愚蠢的问题我失败了:当用子公式替换变量时,ast.parse总是删除给出的右括号和左括号糟糕的最终公式。关于如何保留括号的任何想法? 谢谢!
import ast
list_know_var = ['vx', 'vy', 'vz', 'c']
equation = 'M = V * V / c'
know_equations = {'V': 'vx + 1.'}
# initial equation
parsed_equation = ast.parse(equation)
# the class that automatically dives into the nodes of the AST
# to check for all variables definition
class AdaptEquation(ast.NodeTransformer):
def visit_Name(self, node):
# checking that the variable is know
if node.id not in list_know_var:
if node.id in know_equations.keys():
node = ast.parse(know_equations[node.id]).body[0].value
return node
# adapted equation
AdaptEquation().visit(parsed_equation)
# and its human readable expression
import codegen
print 'expected equation: M = (vx + 1) * (vx + 1) / c'
>>> expected equation: M = (vx + 1) * (vx + 1) / c
print 'adapted equation: ', codegen.to_source(parsed_equation)
>>> adapted equation: M = vx + 1.0 * vx + 1.0 / c