在字符串中查找公式的有效方法

时间:2013-03-04 22:14:15

标签: python regex

说我有字符串testString = "x=4+y and y = 8"

我想运行findIndices(testString)并返回包含公式项

的索引列表

即。这应该返回[0,1,2,3,4,10,11,12,13,14]

我认为这会起作用

find equalSigns
foreach equalSign
   look to the left until you see a space not preceded by an operator
        put current index in  formulalist
   look to the right until you see a space not preceded by an operator
        put current index in formulalist
   put the equalSign index in the formulalist

return formulalist

1)在python中有更有效的方法吗?它是什么? (正则表达式?)

2)如果这是有效的:我如何写“向左看”和“向右看”子程序?

2 个答案:

答案 0 :(得分:2)

我不确定你的意思,但是

string.split("=")  
string.index("=")

例如:

In [1]: a= "y = 25*x  + 42*z"
In [2]: a.split("=")
Out[2]: ['y ', ' 25*x  + 42*z']
In [3]: a.index("=")
Out[3]: 2

可能对您有用。

答案 1 :(得分:2)

正如gnibbler的评论所述,在考虑解析它之前记下语法。也就是说,如果“公式”是一个没有空格的字符串,并且其中至少有一个等号,则以下函数将返回字符串中的公式列表:

def formulas(s):
   return filter(lambda x: '=' in x, s.split())

例如:
formulas('x=4+y and y=8')生成['x=4+y', 'y=8']
formulas("x=4+y and y = 8")生成['x=4+y', '='] formulas('x=4+y and y=8 etc z=47+38*x + y')生成['x=4+y', 'y=8', 'z=47+38*x']

当然,这些结果不是索引列表,字符串y = 8未被视为公式。但是,从更大的角度来看,在进行更详细的处理之前,简化语法并将原始字符串拆分为单独的公式可能更有用。