[英]Convert string expression to mathematical expression?
我正在寻找可以将数学表达式字符串作为输入并通过添加括号来更改它的东西。
举些例子 :
输入 1: "2*4^7"
输出 1: "(2*(4^7))"
输入 2: "sin(x)*3-8^9"
输出 2: "((sin(x)*3)-(8^9))"
输入 3: "(2-8)/6"
输出 3: "((2-8)/6)"
我目前正在尝试对其进行编码,但这需要太多时间,我宁愿专注于其他事情,所以如果你们知道一些可以做到这一点的模块,那就太好了。
我正在使用 python 3
谢谢!
使用ast
模块,您可以解析字符串,然后遍历它以构建您需要的字符串表示:
import ast
def represent(tree):
t = type(tree)
if t == ast.Module:
return represent(tree.body)
elif t == list:
# arithmetic expression should only be one thing
return ", ".join(represent(part) for part in tree)
elif t == ast.Expr:
return represent(tree.value)
elif t == ast.BinOp:
o = type(tree.op)
if o == ast.BitXor:
op = "^"
elif o == ast.Mult:
op = "*"
elif o == ast.Add:
op = "+"
...
return "({}{}{})".format(
represent(tree.left),
op,
represent(tree.right),
)
elif t == ast.Num:
return str(tree.n)
elif t == ast.Name:
return tree.id
elif t == ast.Call:
return "{}({})".format(
represent(tree.func),
represent(tree.args),
)
...
# prints (((sin(x)*2)*x)+4)
print(represent(ast.parse("sin(x)*2*x+4")))
正如@user2357112 在评论中指出的那样,这仅在您限制自己使用 Python 的表达式语法时才有效,最重要的是使用**
而不是^
进行求幂。
只需使用eval(expression)
将a = '2*4^7'
中的字符替换为b=a.replace('^','**')
等等eval(b)
可以使用一些变量
前任:
x= 3
eval("3 * x **2")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.