我想从此处转换文本文件中的行:
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中进行此转换?
由于
答案 0 :(得分:4)
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))
答案 1 :(得分:0)
使用collections.defaultdict
。
您可能希望搜索SO以查找类似问题。
答案 2 :(得分:0)
使用zip你可以这样做:
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(','))))