import sympy from flask import Flask, render_template, request import re from sympy import latex app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/factorize', methods=['GET']) def factorize(): expression = request.args.get('expression') print(expression) if re.match(r'^[a-zA-Z0-9+\-*/()]+$', expression): expression = re.sub(r'([A-Za-z])([A-Za-z])', r'\1*\2', expression) expression = re.sub(r'([0-9])([A-Za-z])', r'\1*\2', expression) else: error = "您输入的字符不合规" return render_template('index.html', error=error) variables = list(set(expression)) try: symbols = sympy.symbols(variables) symbol_dict = dict(zip(variables, symbols)) expr = sympy.sympify(expression, locals=symbol_dict) factors = sympy.factor(expr) result = latex(factors) return render_template('index.html', result=result) except Exception: error_message = "*表示乘法,**表示乘方,括号统一使用小括号,数字与字母中间(或字母与字母中间)的乘号可以省略。" return render_template('index.html', error=error_message) if __name__ == '__main__': app.run(host='0.0.0.0', port=5001)