最近我正在使用Flask和sympy庫開發Web應用程序。用戶在textarea中輸入他的公式,Flask將它作爲一個字符串實現。我希望有可能通過使用sympy函數solve()來計算這個方程的結果。但爲此,我必須將此字符串轉換爲sympy表達式。我怎麼能這樣做?從字符串到sympy表達式
`
from flask import Flask,request,render_template,flash
from sympy import *
from sympy.parsing.sympy_parser import *
x = symbols('x')
app = Flask(__name__)
app.secret_key = 'mysecretkey'
def calculate_():
first_eq = request.form['first_eq']
first_eq2= parse_expr(first_eq)
result = solve(first_eq2)
return result
@app.route("/",methods=['GET', 'POST'])
def myGet():
return render_template("my-form.html")
@app.route("/myPost/",methods=['GET', 'POST'])
def myPost():
answer = request.form['answer']
result_of_answer=solve(Eq(answer),x)
result = calculate_()
try:
if result == result_of_answer:
flash("you got it!")
else:
flash("no, it's wrong")
return render_template("my-form.html")
except:
flash("sorry, wrong type. Try again!")
return render_template("my-form.html")
if __name__ == '__main__':
app.run()`
您可以使用'parse_expr'將字符串's'轉換爲SymPy表達式,如下所示:http://docs.sympy.org/dev/modules/parsing.html –
我試過在我的calculate_ FUNC。它給了我一個sympifyError:'高清calculate_(): first_eq =的Request.Form [ 'first_eq'] first_eq2 = parse_expr(first_eq) 結果=解決(first_eq2) 回報result' – Vasile
什麼'first_eq'的內容?請用你的代碼編輯你的主文章。 –