Python 中的方程解析
我如何(轻松地)获取用户在运行时输入的诸如 "sin(x)*x^2"
之类的字符串,并生成一个可以计算任意值的 Python 函数x
?
How can I (easily) take a string such as "sin(x)*x^2"
which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of x
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您使用 Python 表示法,Python 自己的内部编译器可以解析它。
如果你稍微改变一下符号,你会更高兴。
您将获得一个可以使用的抽象语法树。
Python's own internal compiler can parse this, if you use Python notation.
If your change the notation slightly, you'll be happier.
You get an abstract syntax tree that you can work with.
编辑
解析器
在Python 3.9中已弃用:https://docs.python.org/3/whatsnew/3.9.html#new-parser您可以使用Python
解析器
:它的性能比纯 < code>eval,当然,可以避免代码注入!
EDIT
parser
is deprecated in Python 3.9: https://docs.python.org/3/whatsnew/3.9.html#new-parserYou can use Python
parser
:It performs better than pure
eval
and, of course, avoids code injection!其中
parser
可以使用 PLY、pyparsing、内置分词器、解析器、ast 来定义。不要对用户输入使用
eval
。Where
parser
could be defined using PLY, pyparsing, builtin tokenizer, parser, ast.Don't use
eval
on user input.pyparsing 可能会执行您想要的操作(http://pyparsing.wikispaces.com/),特别是如果字符串来自不受信任的来源。
另请参阅http://pyparsing.wikispaces.com/file/view/fourFn.py 使用它构建的功能相当齐全的计算器。
pyparsing might do what you want (http://pyparsing.wikispaces.com/) especially if the strings are from an untrusted source.
See also http://pyparsing.wikispaces.com/file/view/fourFn.py for a fairly full-featured calculator built with it.
为了强调 JF Sebastian 的建议,“评估”甚至“编译器”解决方案都可能存在微妙的安全漏洞。 输入的可信度如何? 使用“编译器”,您至少可以从 AST 中过滤掉诸如 getattr 查找之类的东西,但我发现使用 PLY 或 pyparsing 来处理此类事情比确保让 Python 帮忙的结果更容易。
此外,“编译器”笨拙且难以使用。 它在 3.0 中已被弃用并删除。 您应该使用“ast”模块(在 2.6 中添加,在 2.5 中作为“_ast”提供)。
To emphasize J.F. Sebastian's advice, 'eval' and even the 'compiler' solutions can be open to subtle security holes. How trustworthy is the input? With 'compiler' you can at least filter out things like getattr lookups from the AST, but I've found it's easier to use PLY or pyparsing for this sort of thing than it is to secure the result of letting Python help out.
Also, 'compiler' is clumsy and hard to use. It's deprecated and removed in 3.0. You should use the 'ast' module (added in 2.6, available in 2.5 as '_ast').
Sage 旨在作为 matlab 替代品,在 介绍视频 它演示了如何处理与您的案例类似的情况。 他们似乎支持多种方法。 由于代码是开源的,您可以浏览并亲自查看作者如何处理此类情况。
Sage is intended as matlab replacement and in intro videos it's demonstrated how similar to yours cases are handled. They seem to be supporting a wide range of approaches. Since the code is open-source you could browse and see for yourself how the authors handle such cases.