3 回答

TA貢獻1859條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超6個贊
另一種選擇是使用csv模塊。
假設(shè)字段之間有一個制表符分隔符:
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'}]
添加回答
舉報