以下是一个示例代码,演示如何使用Python对文本文件进行去重:
def remove_duplicates(input_file, output_file):
lines_seen = set() # 用于存储已经出现过的行
with open(output_file, 'w') as output:
with open(input_file, 'r') as input:
for line in input:
if line not in lines_seen:
output.write(line)
lines_seen.add(line)
# 示例使用
input_file = 'input.txt'
output_file = 'output.txt'
remove_duplicates(input_file, output_file)
上述代码中,我们定义了一个remove_duplicates
函数,它接受一个输入文件和一个输出文件作为参数。函数中使用了一个set
类型的变量lines_seen
来存储已经出现过的行。
函数打开输入文件,并逐行读取其中的内容。对于每一行,首先检查它是否已经存在于lines_seen
集合中。如果不存在,将该行写入输出文件,并将该行添加到lines_seen
集合中。
这样,最终输出的文件中将只包含不重复的行。
你可以根据自己的需求修改文件名和路径,然后调用remove_duplicates
函数即可完成去重操作。
上一篇:按键对数组进行排序/分组
下一篇:按键对字典进行排序