Skip to main content
 首页 » 编程设计

Python如何找出一个文本文件中的唯一元素并输出到另一个文本文件中

2025年05月04日19tuyile006

我有一个名为 sample.txt 的文本文件,内容如下:-

abc   
abc 
egf 
abc  
xyz 
efg 
abc 
xyz 
efg 
xyz 
xyz 

我想要找出独特的元素并将其存储在另一个名为 output.txt 的文本文件中

预期输出:-

abc 
efg 
xyz 
egf 

由于我是 python 和 Stackoverflow 的新手,有人可以从头开始帮助我吗?谢谢

请您参考如下方法:

如果您在类 Unix 系统中工作,则不需要 Python 脚本。管道和过滤器就足够了:

$ cat sample.txt | sort | uniq > output.txt 

正如@devnull 指出的,可以更简洁地写成:

$ sort sample.txt | uniq > output.txt 

如果你真的想用 Python 来做:

seen = set() 
with open('sample.txt') as infile: 
    with open('output.txt', 'w') as outfile: 
        for line in infile: 
            if line not in seen: 
                outfile.write(line) 
                seen.add(line) 

这将按照第一次遇到的顺序打印独特的行。

更简洁的方法是使用 collections.OrderedDict和 with-statemen 的多上下文管理器形式:

from collections import OrderedDict 
 
with open('sample.txt') as infile, open('output.txt', 'w') as outfile: 
    outfile.writelines(OrderedDict.fromkeys(infile))