Skip to main content
 首页 » 编程设计

Python将文件拆分为多个文件并添加额外信息

2024年10月24日11落叶无声

我希望拆分 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 

我相信这是结论性的

最终编辑。