我需要解析一个文本文件,如下所示:
"id"$"date"$"text"
10001$2016-01-11$"[start]
this is some text
[stop]
"
10002$2014-03-12$"[start]
this is some more text
[stop]
"
使用Python放入库中,并将这三个不同的元素(id,日期和文本)作为键。
我不确定如何使用定界符拆分这些元素,以及如何将第一行用作列表中所有元素的键。
这样的事情甚至可以只打印它就行:
infile = open('filename.txt', 'r')
for line in infile:
if "????" in line:
print(line, next(infile))
如果我尝试:
infile = open('filename.txt', 'r')
for line in infile:
if '"text"' in line:
print(next(infile))
它只打印第一行。
理想的情况是:
[{'id':'10001', 'date':'2016-01-11', 'text':'this is some text'},{'id':'10002', 'date':'2014-03-12', 'text':'this is some more text'}]
import csv
with open(path,'rb') as f:
reader = csv.reader(f,delimiter='$')
res = [ {'id':line[0],'date':line[1],'text':line[2]} for line in reader ]
res = res[1:]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句