我希望拆分 2 个文本文件并将它们组合起来:
因此第一个文件称为“Names.txt”,是一个名称列表。它非常大,因此手动将名称放入下一部分是不行的:
Chloe
Megan
Harry
etc...
第二个文件称为“Attributes.txt”,是由 $$$$ 分隔的属性集列表:
attribute1
attribute2
attribute3
$$$$
attribute1
attribute2
etc...
一组属性,每个属性都与第一个文件中的名称相关。然而,我不知道每个集合中有多少属性,因为它是随机的。
我想从第一个文件中获取第一个名称,从第二个文件中获取第一组属性,并将它们写入一个新文件:
Chloe
attribute1
attribute2
attribute3
然后循环它,以便它执行第二个名称并设置等等......
到目前为止我有这段代码:
import os
input_file1 = open('Names.txt', 'r')
input_file2 = open('Attributes.txt', 'r')
lines1 = input_file1.readlines()
def group_by_person(some_source):
buffer = []
for line in (some_source):
if line.startswith("$$$$"):
if buffer: yield buffer
buffer = [line]
else:
buffer.append(line)
yield buffer
i = 0
name1 = lines1[i]
name2 = name1[:-1]
g = 0
while os.path.exists(name2 + '%s.txt' % g):
g += 1
with open(name2 + '%s.txt' % g, 'w') as f:
with input_file2 as source:
for lines2 in group_by_name(source):
f.write(lines2[i])
i += 1
有人可以帮忙吗?
最佳答案
我认为这就是您想要实现的目标,如果我错了,请发表评论:
def group_by_person(names_file, attributes_files):
with open(names_file) as names, open(attributes_files) as attributes:
for name in names:
line = [name.strip()]
for attribute in attributes:
if attribute.startswith("$$$$"):
break
line.append(attribute.strip())
print line
yield line
names_count = {}
for name in group_by_person('Names.txt', 'Attributes.txt'):
n = name[0]
names_count[n] = names_count.setdefault(n, 0) + 1
with open("%s%s.txt" % (n, names_count[n]), 'w') as f:
f.write('\n'.join(name))
测试结果:
名称.txt:
Chloe
Megan
Chloe
属性.txt:
attribute1
attribute2
attribute3
$$$$
attribute4
attribute5
$$$$
attribute6
输出文件:
Chloe1.txt, Megan1.txt, Chloe2.txt
克洛伊1:
Chloe
attribute1
attribute2
attribute3
梅根1.txt
Megan
attribute4
attribute5
Chloe2.txt:
Chloe
attribute6
我相信这是决定性的
最终编辑。
关于Python 将一个文件拆分为多个文件并添加额外信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992311/