引言在处理文本文件时,删除重复的行是一个常见的任务。Python 提供了多种方法来实现这一目标,无论是通过简单的文本编辑还是使用更高级的编程技巧。本文将介绍几种简单而有效的方法来使用 Python 删...
在处理文本文件时,删除重复的行是一个常见的任务。Python 提供了多种方法来实现这一目标,无论是通过简单的文本编辑还是使用更高级的编程技巧。本文将介绍几种简单而有效的方法来使用 Python 删除 TXT 文件中的重复行,从而优化文档,提高工作效率。
Python 的标准库中包含了一个非常实用的模块 collections,其中的 OrderedDict 类可以用来去除重复的行。
OrderedDict 来去除重复的行。from collections import OrderedDict
def remove_duplicate_lines(input_file, output_file): with open(input_file, 'r') as file: lines = file.readlines() unique_lines = list(OrderedDict.fromkeys(lines)) with open(output_file, 'w') as file: file.writelines(unique_lines)
# 使用函数
remove_duplicate_lines('input.txt', 'output.txt')集合(Set)是一个无序的不重复元素序列,可以用来快速去除重复的行。
def remove_duplicate_lines_with_set(input_file, output_file): with open(input_file, 'r') as file: lines = file.readlines() unique_lines = list(set(lines)) with open(output_file, 'w') as file: file.writelines(unique_lines)
# 使用函数
remove_duplicate_lines_with_set('input.txt', 'output.txt')如果你需要更复杂的逻辑来匹配和删除重复行,可以使用正则表达式。
re 模块来匹配特定的模式。re.sub 或 re.findall 来处理文本。import re
def remove_duplicate_lines_with_regex(input_file, output_file, pattern): with open(input_file, 'r') as file: content = file.read() unique_content = re.sub(pattern, '', content, count=1) with open(output_file, 'w') as file: file.write(unique_content)
# 使用函数
remove_duplicate_lines_with_regex('input.txt', 'output.txt', r'\n+')以上是几种使用 Python 删除 TXT 文件中重复行的常用方法。根据你的具体需求,你可以选择最适合你的方法。这些方法不仅可以帮助你优化文档,还可以提高你的编程技能。希望这篇文章能帮助你轻松掌握这些技巧!