将方程式解析为Python中的元组列表 [英] Parse equation to list of tuples in Python
问题描述
我想解析方程式并获取元组列表. 例如,当我输入
I want to parse equations and get a list of tuples. For example, when I enter
2x = 4+3y,
我想得到
[('', '2', 'x', '='), ('','4','',''), ('+','3','y','')]
到目前为止,这是我的正则表达式:
This is my regex so far:
([+-]*)([0-9]+)([a-z]*)([<=>]*)
对于上面的查询,它工作正常,但不能捕获诸如
It works fine for the above query but it does not capture equations like
2 = x +3y
,(其中x没有任何系数)
2 = x +3y
, (where x does not have any coefficient)
我该如何捕捉?
推荐答案
如果将系数的量词从+
(一个或多个)更改为*
(零或更多),那么您应该得到想要的结果.由于所有的量词现在都为*
,因此您还将得到一个空字符串匹配,但是您可以过滤掉该匹配.
If you change the quantifier on the coefficient from +
(one or more) to *
(zero or more) then you should get the result you are after. You will also get an empty string match due to all the quantifiers now being *
but you can filter out that match.
>>> import re
>>> e1 = "2x=4+3y"
>>> e2 = "2=x+3y"
>>> re.findall("([+-]*)([0-9]*)([a-z]*)([<=>]*)", e1)
[('', '2', 'x', '='), ('', '4', '', ''), ('+', '3', 'y', ''), ('', '', '', '')]
>>> re.findall("([+-]*)([0-9]*)([a-z]*)([<=>]*)", e2)
[('', '2', '', '='), ('', '', 'x', ''), ('+', '3', 'y', ''), ('', '', '', '')]
注意:虽然这可以解决您的直接问题,但这不是解析infix方程的好方法.
Note: whilst this solves your direct question this is not a good approach to parsing infix equations.
这篇关于将方程式解析为Python中的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!