2010-11-18 50 views
0

如何解析以下文件,並將每行轉換爲列表元素(每行開始處有空格)?不幸的是我在正則表達式總是吸:/所以把這個:將多行文件的內容更改爲列表

32.42.4.120', '32.42.4.127 
32.42.5.128', '32.42.5.255 
32.42.15.136', '32.42.15.143 
32.58.129.0', '32.58.129.7 
32.58.131.0', '32.58.131.63 
46.7.0.0', '46.7.255.255 

到一個列表:

('32.42.4.120', '32.42.4.127'), 
('32.42.5.128', '32.42.5.255'), 
('32.42.15.136', '32.42.15.143'), 
('32.58.129.0', '32.58.129.7'), 
('32.58.131.0', '32.58.131.63'), 
+0

最後一行發生了什麼? – SilentGhost 2010-11-18 14:38:44

回答

1

這個怎麼樣? (如果我錯了,至少讓我知道下來之前投票)

>>> x = [tuple(line.strip().split("', '")) for line in open('file')] 
>>> x 
[('32.42.4.120', '32.42.4.127'), ('32.42.5.128', '32.42.5.255'), ('32.42.15.136', '32.42.15.143'), ('32.58.129.0', '32.58.129.7'), ('32.58.131.0', '32.58.131.63'), ('46.7.0.0', '46.7.255.255')] 
1

沒有需要的正則表達式:

l = [] 

with open("name_file", "r") as f: 
    for line in f: 
     l.append(line.split(", ")) 
如果要刪除第一個空間

並有元組你可以做:

l = [] 

with open("name_file", "r") as f: 
    for line in f: 
     data = line.split(", ") 
     l.append((data[0].strip(), data[1].strip())) 
+0

缺少尼特 - 他有領先的空白,所以它需要是line.strip()。split() – bgporter 2010-11-18 14:38:39

1
l = [] 
f = open("test_data.txt") 
for line in f: 
elems = line[1:-1].split("', '") 
l.append((elems[0], elems[1])) 
f.close() 

print l 

輸出:

[('32 .42.4.120' ,'32 .42.4.127' ) ,('32.42.5.128','32.42.5.255'),('32.42.15.136','32.42.15.143'),('32.58.129.0','32.58.129.7'),('32.58.131.0', '32 .58.131.63'),('46.7.0.0','46 .7.255.25')]