Python中的方程解析 [英] Equation parsing in Python

查看:23
本文介绍了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?

推荐答案

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.

import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )

您将获得一个可以使用的抽象语法树.

You get an abstract syntax tree that you can work with.

这篇关于Python中的方程解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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