Python名称节点替换删除括号

时间:2014-03-16 21:01:23

标签: python equation abstract-syntax-tree

我正在尝试使用最终的子公式在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

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。使用Astor代替 Codegen。 虽然我很欣赏Codegen,但我必须说它的马车。 Astor建立在Codegen之上,更新,功能更多。以下是使用Astor的一个例子:

import astor
import ast
test_code = "x=1-(x+y)"
abstract_syntax_tree = ast.parse(test_code)
print astor.to_source(abstract_syntax_tree)
print 'done'

#output
#x = (1 - (x + y))
#done
相关问题