我试图使用 Python 的 AST 模块将 Python 数学表达式转换为后缀表示法。以下是我目前的代码:
我正在尝试理解如何将复杂的中缀数学表达式转换为后缀表达式,并发送给SWIG C包装器,为此我正在尝试使用AST模块。是否有人可以提供帮助?
import parser
import ast
from math import sin, cos, tan
formulas = [
"1+2",
"1+2*3",
"1/2",
"(1+2)*3",
"sin(x)*x**2",
"cos(x)",
"True and False",
"sin(w*time)"
]
class v(ast.NodeVisitor):
def __init__(self):
self.tokens = []
def f_continue(self, node):
super(v, self).generic_visit(node)
def visit_Add(self, node):
self.tokens.append('+')
self.f_continue(node)
def visit_And(self, node):
self.tokens.append('&&')
self.f_continue(node)
def visit_BinOp(self, node):
# print('visit_BinOp')
# for child in ast.iter_fields(node):
# print(' child %s ' % str(child))
self.f_continue(node)
def visit_BoolOp(self, node):
# print('visit_BoolOp')
self.f_continue(node)
def visit_Call(self, node):
# print('visit_Call')
self.f_continue(node)
def visit_Div(self, node):
self.tokens.append('/')
self.f_continue(node)
def visit_Expr(self, node):
# print('visit_Expr')
self.f_continue(node)
def visit_Import(self, stmt_import):
for alias in stmt_import.names:
print('import name "%s"' % alias.name)
print('import object %s' % alias)
self.f_continue(stmt_import)
def visit_Load(self, node):
# print('visit_Load')
self.f_continue(node)
def visit_Module(self, node):
# print('visit_Module')
self.f_continue(node)
def visit_Mult(self, node):
self.tokens.append('*')
self.f_continue(node)
def visit_Name(self, node):
self.tokens.append(node.id)
self.f_continue(node)
def visit_NameConstant(self, node):
self.tokens.append(node.value)
self.f_continue(node)
def visit_Num(self, node):
self.tokens.append(node.n)
self.f_continue(node)
def visit_Pow(self, node):
self.tokens.append('pow')
self.f_continue(node)
for index, f in enumerate(formulas):
print('{} - {:*^76}'.format(index, f))
visitor = v()
visitor.visit(ast.parse(f))
print(visitor.tokens)
print()
# 0 - ************************************1+2*************************************
# [1, '+', 2]
# 1 - ***********************************1+2*3************************************
# [1, '+', 2, '*', 3]
# 2 - ************************************1/2*************************************
# [1, '/', 2]
# 3 - **********************************(1+2)*3***********************************
# [1, '+', 2, '*', 3]
# 4 - ********************************sin(x)*x**2*********************************
# ['sin', 'x', '*', 'x', 'pow', 2]
# 5 - ***********************************cos(x)***********************************
# ['cos', 'x']
# 6 - *******************************True and False*******************************
# ['&&', True, False]
# 7 - ********************************sin(w*time)*********************************
# ['sin', 'w', '*', 'time']
我正在尝试理解如何将复杂的中缀数学表达式转换为后缀表达式,并发送给SWIG C包装器,为此我正在尝试使用AST模块。是否有人可以提供帮助?