[英]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.