首页 > 解决方案 > 获取文件中的重复行

问题描述

处理数千行的文件

试图找到准确重复的行(2次)

from collections import Counter
with open('log.txt') as f:
    string = f.readlines()
    c = Counter(string)
    print c 

它给了我所有重复行的结果,但我需要得到重复行(仅 2 次)

标签: python

解决方案


您正在打印所有字符串,而不仅仅是重复的字符串,要仅打印重复两次的字符串,您可以打印计数为 2 的字符串。

from collections import Counter
with open('log.txt') as f:
    string = f.readlines()
    c = Counter(string)
    for line, count in c.items():
        if count==2:
            print(line) 

推荐阅读