此python代码未解决方程式 [英] This python code is not solving equations

查看:55
本文介绍了此python代码未解决方程式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于即时通讯程序的聊天机器人,我正在尝试为其创建数学求解器,但是它无法将方程式的解决方案发送给即时通讯程序,而是发送了方程式.

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 question Evaluating a mathematical expression in a string

这篇关于此python代码未解决方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆