将方程式解析为Python中的元组列表

时间:2019-02-23 10:31:17

标签: python tuples equation

我想解析方程式并获取元组列表。 例如,当我输入

gradlew.bat html:dist --daemon

我想得到

Sub Sum_and_Dedupe()
With Worksheets("data")
    'deal with the block of data radiating out from A1
    With .Cells(1, 1).CurrentRegion
        'step off the header and make one column wider
        With .Resize(.Rows.Count - 1, .Columns.Count + 1).Offset(1, 0)
            .Columns(.Columns.Count).Formula = "=sumifs(c:c, i:i, i2)"
            .Columns(3) = .Columns(.Columns.Count).Value
            .Columns(.Columns.Count).Delete
        End With

        'remove duplicates
        .RemoveDuplicates Columns:=Array(9), Header:=xlYes
    End With
    .UsedRange
End With
End Sub

到目前为止,这是我的正则表达式:

2x = 4+3y, 

它对于上面的查询工作正常,但不能捕获像

这样的方程式

[('', '2', 'x', '='), ('','4','',''), ('+','3','y','')] ,(其中x没有任何系数)

我该如何捕捉?

2 个答案:

答案 0 :(得分:0)

(\d*)(\w*) *(=) *(\d*)(\w*) *[+|\-|*|/] *(\d*)(\w*)

该正则表达式如何?

它将所有操作数和运算符分开。 (并且在操作数内部它还会拆分数字和变量)。

我通常使用https://regex101.com/来测试正则表达式,因此您可以在那里进行实时更改来构建正则表达式。

答案 1 :(得分:0)

如果您将系数的量词从+ (一个或多个)更改为* (零个或多个),那么您应该得到你想要的结果。由于所有的量词现在都是*,因此您还会得到一个空字符串匹配,但是您可以过滤掉该匹配。

>>> 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方程的好方法。