2014-02-20 180 views
1

我有一個文本文件是這樣的:拆分一個字符串並將子字符串保存爲字典。 Python的

771 776 #1 556.766700(2) 
538 #2 1069.652700(2) 
531 #3 1074.407600(2) 
81 84 89 94 111 #4 1501.062900(2) 
85 91 #5 782.298900(3) 
32 42 66 71 90 95 101 #6 904.016500(3) 

我想要分割並保存子不同的變量如下: 例如,在第1行:

scans= 771 776, uid = 1 mz = 556.766700, z = 2 

我想使用下面的代碼,但我需要用正則表達式的幫助:

f = open(filename, 'r') 
par_info=[] 
for rows in f: 
    re.sub('\#(.+)\s(.+)\((.+)\+', scans=\g<1>, uid=\g<2>, mz = int(\g<3>), z=int(\g<4>), rest) 
    info={'sc_num':scans, 'ident':uid, 'mass':mz, 'charge':z} 
    par_info.append(info) 
+0

當你運行你的代碼時會發生什麼? –

+0

我實際上只是嘗試了一個字符串的正則表達式,並且得到了以下錯誤:SyntaxError:行繼續字符後的意外字符 – kkhatri99

+1

請注意,您的代碼中有許多缺少引號和'='在'info'中應該有':'字典。 – DSM

回答

5

您可以使用命名組:

>>> import pprint 
>>> import re 
>>> r = re.compile(r'(?P<scans>.*?)\s+#(?P<uid>\d+)\s+(?P<mz>\d+\.\d+)\((?P<z>\d+)\)') 
>>> with open('abc1') as f: 
     par_info = [r.search(line).groupdict() for line in f] 
...  
>>> pprint.pprint(par_info) 
[{'mz': '556.766700', 'scans': '771 776', 'uid': '1', 'z': '2'}, 
{'mz': '1069.652700', 'scans': '538', 'uid': '2', 'z': '2'}, 
{'mz': '1074.407600', 'scans': '531', 'uid': '3', 'z': '2'}, 
{'mz': '1501.062900', 'scans': '81 84 89 94 111', 'uid': '4', 'z': '2'}, 
{'mz': '782.298900', 'scans': '85 91', 'uid': '5', 'z': '3'}, 
{'mz': '904.016500', 'scans': '32 42 66 71 90 95 101', 'uid': '6', 'z': '3'}] 
1
import re 
pattern = re.compile("(\d+\s*\d*)\s+#(\d+)\s+([\d\.]+)\s*\((\d+)\)") 
for line in open("Input.txt"): 
    scans, uid, mz, z = pattern.findall(line)[0] 
    print scans, uid, mz, z 

輸出

771 776 1 556.766700 2 
538 2 1069.652700 2 
531 3 1074.407600 2 
94 111 4 1501.062900 2 
85 91 5 782.298900 3 
95 101 6 904.016500 3 

正則表達式演示

Regular expression visualization

Debuggex Demo

+0

謝謝!這是非常豐富的! – kkhatri99

0

我會用split如果在本例中的數據始終結構以及

par_info = [] 
with open(filename, 'r') as f: 
    for line in f: 
     scan, other = line.split("#") 
     uid, more = other.split() 
     mz, z = other.split('(') 
     z = z.replace(')','') 
     info = {'sc_num': scans, 'ident': uid, 'mass': mz, 'charge': z} 
     par_info.append(info) 
0

此正則表達式的作品,然後你可以壓縮的發現的組在一起,把它們變成一個字典:

In [1]: import re 

In [2]: a = "771 776 #1 556.766700(2)" 

In [3]: c = re.compile(r'([\d\s]+)\s#(\d)+\s([\d\.]+)\((\d+)\)') 

In [4]: titles = ('sc_num', 'ident', 'mass', 'charge') 

In [5]: dict(zip(titles, c.search(a).groups())) 
Out[5]: {'charge': '2', 'ident': '1', 'mass': '556.766700', 'sc_num': '771 776'} 

把它和你的代碼放在一起,你會得到:

f = open(filename, 'r') 
c = re.compile(r'([\d\s]+)\s#(\d)+\s([\d\.]+)\((\d+)\)') 
titles = ('sc_num', 'ident', 'mass', 'charge') 
par_info=[] 
for row in f: 
    info = dict(zip(titles, c.search(row).groups())) 
    par_info.append(info) 
相關問題