以下是一个解决方法,使用Python 3.6的代码示例:
from collections import Counter
def mark_duplicate_lines(file_path):
# 打开文件并读取所有行
with open(file_path, 'r') as file:
lines = file.readlines()
# 统计每行出现的次数
line_counts = Counter(lines)
# 标记重复行并添加范围数字
marked_lines = []
for i, line in enumerate(lines):
if line_counts[line] > 1: # 如果行重复
marked_line = f"{i+1}: {line}" # 添加范围数字
marked_lines.append(marked_line)
else:
marked_lines.append(line)
# 将标记的行写回文件
with open(file_path, 'w') as file:
file.writelines(marked_lines)
# 示例用法
mark_duplicate_lines('input.txt')
上述代码首先使用Counter
类计算每行出现的次数。然后,它遍历文件的每一行,在重复行上添加范围数字,并将标记的行写回文件中。
请确保将file_path
参数替换为您要处理的文件的路径。
上一篇:标记指针CRTP访问器类
下一篇:标记状态更新的可能性