我希望使用Python将纯结构化文本文件转换为CSV格式。
输入如下所示
[-------- 1 -------]
Version: 2
Stream: 5
Account: A
[...]
[------- 2 --------]
Version: 3
Stream: 6
Account: B
[...]输出应该如下所示:
Version; Stream; Account; [...]
2; 5; A; [...]
3; 6; B; [...]也就是说,输入是由[----<sequence number>----]分隔并包含<key>: <values>-pairs的结构化文本记录,输出应该是CSV,每行包含一条记录。
我能够将<key>: <values>-pairs检索成CSV格式
colonseperated = re.compile(' *(.+) *: *(.+) *')
fixedfields = re.compile('(\d{3} \w{7}) +(.*)')-但我很难识别结构化文本记录的开头和结尾,以及重写为CSV行记录。此外,我希望能够分离不同类型的记录,即区分-比如说- Version: 2和Version: 3类型的记录。
发布于 2013-10-17 21:12:45
阅读这份清单并不难:
def read_records(iterable):
record = {}
for line in iterable:
if line.startswith('[------'):
# new record, yield previous
if record:
yield record
record = {}
continue
key, value = line.strip().split(':', 1)
record[key.strip()] = value.strip()
# file done, yield last record
if record:
yield record这将从输入文件中生成字典。
由此,您可以使用csv模块,特别是 class生成CSV输出。
# List *all* possible keys, in the order the output file should list them
headers = ('Version', 'Stream', 'Account', ...)
with open(inputfile) as infile, open(outputfile, 'wb') as outfile:
records = read_records(infile)
writer = csv.DictWriter(outfile, headers, delimiter=';')
writer.writeheader()
# and write
writer.writerows(records)从记录中丢失的任何头键都将保留该记录的该列为空。遗漏的任何额外标题都会引发异常;要么将这些标头添加到headers元组,要么将extrasaction关键字设置为DictWriter()构造函数为'ignore'。
https://stackoverflow.com/questions/19437207
复制相似问题