将多行文件的内容更改为列表

时间:2010-11-18 14:32:58

标签: python regex parsing list

如何解析以下文件,并将每一行转换为列表元素(每行开头有空格)?不幸的是我总是在正则表达式上吮吸:/所以转过来:

 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'),

3 个答案:

答案 0 :(得分: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()))

答案 1 :(得分: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')]

答案 2 :(得分: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')]