3 回答
TA贡献1859条经验 获得超6个赞
对我来说,这看起来像是固定宽度的格式。
如果是这样,您可以这样做:
data={}
ss=((0,19),(20,41),(42,80))
with open('/tmp/p.txt','r') as f:
for n,line in enumerate(f):
fields={}
for i,j in ss:
field=line[i:j]
t=field.split(':')
fields[t[0].strip()]=t[1].strip()
data[n]=fields
print data
印刷:
{0: {'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'}, 1: {'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}}
如果您想要一个列表:
data=[]
ss=((0,19),(20,41),(42,80))
with open('/tmp/p.txt','r') as f:
for n,line in enumerate(f):
fields={}
for i,j in ss:
field=line[i:j]
t=field.split(':')
fields[t[0].strip()]=t[1].strip()
data.append(fields)
无论哪种情况,您都可以访问:
>>> data[0]['comment']
'outstanding'
TA贡献1895条经验 获得超3个赞
像这样的东西:
>>> with open("abc") as f:
lis = []
for line in f:
lis.append(dict( map(str.strip, x.split(":")) for x in line.split(" "*8)))
...
>>> lis
[{'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'},
{'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}
]
>>> lis[0]['comment'] #access 'comment' field on line 1
'outstanding'
>>> lis[1]['field 2'] # access 'field 2' on line 2
''
TA贡献1802条经验 获得超6个赞
另一种选择是使用csv模块。
假设字段之间有一个制表符分隔符:
import StringIO
import csv
input_data = StringIO.StringIO("""field 1: dog field 2: first comment: outstanding
field 1: cat field 2: comment: some comment about the cat""")
data = []
for row in csv.reader(input_data, delimiter="\t"):
line = {}
for item in row:
value = item.split(":")
line[value[0]] = value[1].strip()
data.append(line)
print data
印刷
[{'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'}, {'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}]
添加回答
举报