python – 从字符串到sympy表达式

最近我使用Flask和sympy库开发了一个Web应用程序.用户在textarea中输入他的等式,Flask将其作为字符串取代.我想通过使用sympy函数solve()来计算这个等式的结果.但为此我必须将此字符串转换为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()`

解决方法:

你正在寻找的功能是有道理的. http://docs.sympy.org/latest/modules/core.html#sympy.core.sympify.sympify

上一篇:python – sympy v1.0 factor是否给出(2 * 4)(2 * 4)/(2 x)的错误答案?


下一篇:FireFox Prevent this page from creating addtional dialogs 火狐浏览器 设置 阻止此页面创建更多对话框