我想线转换成文本文件,从这个:在Python转换的大量项目进入单项线列表
animal cat, mouse, dog, horse
numbers 22,45,124,87
这样:
animal cat
animal mouse
animal dog
animal horse
numbers 22
numbers 45
numbers 124
numbers 87
我怎么会做这种转换在python中?
谢谢
我想线转换成文本文件,从这个:在Python转换的大量项目进入单项线列表
animal cat, mouse, dog, horse
numbers 22,45,124,87
这样:
animal cat
animal mouse
animal dog
animal horse
numbers 22
numbers 45
numbers 124
numbers 87
我怎么会做这种转换在python中?
谢谢
使用collections.defaultdict
。
你可能想搜索SO的类似问题。
with open('thefile.txt') as fin:
with open('result.txt') as fou:
for line in fin:
key, values = line.split(None, 1)
vs = [x.strip() for x in values.split(',')]
for v in vs:
fou.write('%s %s\n' % (key, v))
拉链,你可以这样做:
inp="""animal cat, mouse, dog, horse
numbers 22,45,124,87
"""
for line in inp.splitlines():
key,data = line.split(None,1)
print '\n'.join("%s%8s" % line
for line in zip([key.strip()] * (data.count(',')+1),
(item.strip() for item in data.split(','))))