从字符串中提取值

时间:2010-01-19 13:36:02

标签: python string

我正在尝试从字符串中提取值,我试图让re.match工作,但没有任何运气。字符串是:

'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'

我试过了:

 map(int,re.search("Value\s*=\s*").group(1))

还有:

'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'.split(' = ')

我不确定还有什么要添加或做的。我想检索属性'Value, Max, Step'及其值。反正有吗?

感谢您的帮助

4 个答案:

答案 0 :(得分:6)

对于特定的字符串,以下内容将其解析为字典:

s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
d = {}
for pair in [val.split('=') for val in s.split('\r\n')[1:-1]]:
    d[pair[0]] = int(pair[1])

答案 1 :(得分:3)

>>> s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
>>> bits = s.split('\r\n')
>>> val, max_val, step = [int(bits[i].partition(' = ')[2]) for i in [1, 3, 4]]
>>> val
1800
>>> max_val
3600
>>> step
1

答案 2 :(得分:0)

s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
data = {}

for l in s.split('\r\n'):
     if " = " in l:
             k,v = l.split(" = ")
             data[k] = int(v)

print data

答案 3 :(得分:0)

您正在尝试使用正则表达式,但我认为您可以简单地将其拆分为\r\n,然后将值与=一起使用。

类似的东西:

s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
dct = {}
arr = [ss for ss in s.split('\r\n') if '=' in ss]
for e in arr:
    k, v = e.split(' = ')
    dct[k] = v
print dct