问题描述
我有一个用于即时通讯程序的聊天机器人,我正在尝试为其创建数学求解器,但是它无法将方程式的解决方案发送给即时通讯程序,而是发送了方程式.
I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.
如果即时通讯程序中的某人发送了"solve:2 + 2",则此程序应将其发送给他们"4",而不是"2 + 2".
If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".
主要问题:
if (parser.getPayload().lower()[:6]=="solve:"):
parser.sendGroupMessage(parser.getTargetID(), str(parser.getPayload()[7:]))
输出:
测试:我测试了一些东西,并且工作正常.如果添加此代码,程序将发送方程式的解:
Test:I tested something and that's working properly. If I add this code, program will send solution of equation:
if (parser.getPayload().lower()=="test"):
parser.sendGroupMessage(parser.getTargetID(), str(2 + 2 -3 + 8 * 7))
输出:完美运行
推荐答案
执行此操作需要以字符串形式评估数学表达式.
What you need to do this evaluating math expressions in string form.
但是,如果您只是eval
所提供的东西,则用户输入很危险. Python的eval()在不受信任的字符串上的安全性吗?
However, user inputs are dangerous if you are just eval
things whatever they give you. Security of Python's eval() on untrusted strings?
您可以使用ast.literal_eval
降低风险.
或者您可以使用以下问题的答案中的评估者评估字符串中的数学表达式
Or you can use a evaluator from answers of following questionEvaluating a mathematical expression in a string
这篇关于此python代码未解决方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!