标记化Python中的数学表达式 [英] Tokenize a mathematical expression in Python

查看:92
本文介绍了标记化Python中的数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个函数来标记数学表达式,将输入字符串转换为标记列表,但是没有成功.有没有一种简单的方法可以在Python中做到这一点?例如,给定表达式

I tried to write a function to tokenize a mathematical expression, converting an input string into a list of tokens, but without success. Is there an easy way to do this in Python? For example, given the expression

sin(1 + 2 * x)+ tan(2.123 * x),

sin( 1 + 2 * x ) + tan( 2.123 * x ),

我想获取列表

[ 'sin', '(', '1', '+', '2', '*', 'x', ')', '+', 'tan', '(', '2.123', '*', 'x', ')' ]

提前谢谢!

推荐答案

您可以使用tokenize -module. http://docs.python.org/2/library/tokenize.html 这是一个示例

You can use tokenize-module. http://docs.python.org/2/library/tokenize.html Here is an example

>>> s = "sin( 1 + 2 * x ) + tan( 2.123 * x "
>>> import tokenize
>>> from StringIO import StringIO
>>> tokenize.tokenize(StringIO(s).readline)
1,0-1,3:    NAME    'sin'
1,3-1,4:    OP  '('
1,5-1,6:    NUMBER  '1'
1,7-1,8:    OP  '+'
1,9-1,10:   NUMBER  '2'
1,11-1,12:  OP  '*'
1,13-1,14:  NAME    'x'
1,15-1,16:  OP  ')'
1,17-1,18:  OP  '+'
1,19-1,22:  NAME    'tan'
1,22-1,23:  OP  '('
1,24-1,29:  NUMBER  '2.123'
1,30-1,31:  OP  '*'
1,32-1,33:  NAME    'x'
# and now occurs some error you have to catch

还有另一种使用正则表达式的方法:

And there is an other approach using regular expressions:

这里是reg-ex解释的链接,该网站还是测试/探索regex的绝佳工具:

Here is the link for the explanation of the reg-ex and this site is also a great tool for testing/exploring regex: http://regex101.com/r/bP6kH1

>>> s = "sin( 1 + 2 * x ) + tan( 2.123 * x "
>>> import re
>>> re.findall(r"(\b\w*[\.]?\w+\b|[\(\)\+\*\-\/])", s)
['sin', '(', '1', '+', '2', '*', 'x', ')', '+', 'tan', '(', '2.123', '*', 'x']

这篇关于标记化Python中的数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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