将角色移动到集合列表python的开头

bq9c1y66  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(99)

比较文件并按顺序列出它们。如果有一个'〉',我如何在使用下面的代码比较它们之后将其移动到输出文件的开头。当前〉被添加到所有行

S = set()
for name in ['some_file_2.txt', 'some_file_3.txt']:
    with open(name, 'r') as f:
        S.update(f.read().split('\n'))

with open('some_file_1.txt', 'r') as f, open('some_output_file.txt', 'w') as fo:
    for line in f:
        fo.write('|'.join(sorted(line.strip().split('|'), key=lambda x: x not in S))+'\n')

输入文件
file 1条目

>winter|mountain|snow
winter weather
>skate|slide
winter activities
>ice|water|freeze|melt
winter temperatures

file 2条目

water
juice
mountain

file 3条目

sea
ocean
slide
climb

希望输出如下所示

>mountain|winter|snow
winter weather
>slide|skate
winter activities
>water|ice|freeze|melt
winter temperatures

如何修改或更新上述脚本,使>位于集合的开头/停留在集合的开头,并且在排序时不会移位?

gg0vcinb

gg0vcinb1#

在拆分之前删除>,然后在写入时将其添加回去。

with open('some_file_1.txt', 'r') as f, open('some_output_file.txt', 'w') as fo:
    for line in f:
        if line.startswith('>'):
            line = line.strip()[1:]
            fo.write('>' + '|'.join(sorted(line.split('|'), key=lambda x: x not in S))+'\n')
        else:
            fo.write(line)

相关问题