並且怎麼樣不使用正則表達式,但使用解析器呢?
from pyparsing import *
integer = Word(nums).setParseAction(lambda t:int(t[0]))
variable = Word(alphas,exact=1)
operand = integer | variable
expop = Literal('^')
signop = oneOf('+ -')
multop = oneOf('* /')
plusop = oneOf('+ -')
factop = Literal('!')
equalop = Literal('=')
expr = operatorPrecedence(operand,
[("=", 2, opAssoc.LEFT),
("+", 2, opAssoc.RIGHT),]
)
test=['60=60', '70=10+20', '100=1+2+42+67']
for t in test:
print t, u'→', expr.parseString(t)
print
這將隨後輸出:
60=60 → [[60, '=', 60]]
70=10+20 → [[[70, '=', 10], '+', 20]]
100=1+2+42+67 → [[[100, '=', 1], '+', [2, '+', [42, '+', 67]]]]
然後拿到整數,你只需要扁平化樹,查找所有整數。
的另一種方式,我覺得稍顯不足優雅,不做字符串的語法檢查,將拆就+
和=
字符串:
for t in test:
head, tail = t.split('=')
values = [head] + tail.split('+')
print t, u'→', values
這給:
60=60 → ['60', '60']
70=10+20 → ['70', '10', '20']
100=1+2+42+67 → ['100', '1', '2', '42', '67']
最後,我們可以嘗試找到一個正則表達式的魔彈來回答你的問題,但說實話,這不會是我解決這個問題的方法。
N.B:扁平化的列表,這裏有一個辦法:
def flatten(seq):
res = []
for item in seq:
if (isinstance(item, (tuple, list))):
res.extend(flatten(item))
else:
res.append(item)
return res
是否有總有兩個'+'經營者? – gtlambert
不,我會添加更多示例 – dmzkrsk
查看我的帖子。您可以很容易地評估+ - 和十進制數字。 – Saleem