从python中的字符串中收集数字

时间:2013-11-08 16:06:44

标签: python regex file

我如何收集数字0.0,0.64和0.08,0.72并将它们放入变量中? 字符串看起来像这样

{"object" "rectangle" "param1" {"Type1" "Type2"} "param2" {{0.0 0.64} {0.08 0.72}} "smth" 0 "point1" 0 "point2" }

我正在尝试在Python上执行此操作

2 个答案:

答案 0 :(得分:1)

以下是获取这些数字的方法:

>>> from re import findall
>>> mystr = """
... {"object" "rectangle" "param1" {"Type1" "Type2"} "param2" {{0.0 0.64} {0.08 0.72}} "smth" 0 "point1" 0 "point2" }
... """
>>> findall("-?\d+\.\d+", mystr)
['0.0', '0.64', '0.08', '0.72']
>>> var1, var2, var3, var4 = findall("-?\d+\.\d+", mystr)
>>> var1
'0.0'
>>> var4
'0.72'
>>>

或者,如果你想将它们作为花车,你可以这样做:

>>> var1, var2, var3, var4 = map(float, findall("-?\d+\.\d+", mystr))
>>> var1
0.0
>>> var4
0.72
>>>

最后,这是正则表达式模式的细分:

-?   # An optional hyphen (for negative numbers)
\d+  # One or more digits
\.   # A period (the decimal point)
\d+  # One or more digits

答案 1 :(得分:1)

这看起来类似于JSON类型文件,但并不完全。如果你可以使用python的内置JSON库正确格式化生活可能会更容易。但是,如果它始终是相同类型的格式,您可以计算这个正则表达式来做一个快速而肮脏的工作:

data = """"{"object" "rectangle" "param1" {"Type1" "Type2"} "param2" {{0.0 0.64} {0.08 0.72}} "smth" 0 "point1" 0 "point2" }"""
r = re.compile('"param2" {{(\d+\.\d+) (\d+\.\d+)} {(\d+\.\d+) (\d+\.\d+)}}')
m = r.search(data)
[float(m.group(i)) for i in range(1,5)]

输出:

[0.0, 0.64, 0.08, 0.72]