最近我正在使用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'的内容?请用你的代码编辑你的主文章。 –