2010-01-19 127 views
4

我想從字符串中提取值,我試圖讓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'及其值的屬性。無論如何要做到這一點?

感謝所有幫助

回答

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]) 
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 
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 
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