获取文件中的重复行

2024-03-28 13:49:03 发布

您现在位置:Python中文网/ 问答频道 /正文

用数千行处理文件

试图找出哪一行完全重复(2次)

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

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


Tags: 文件fromimporttxtlogstringaswith
3条回答

计数器对象还提供有关行出现频率的信息。 您可以使用列表理解等方法对其进行过滤。 这将打印文件中正好出现两次的所有行

with open('log.txt') as f:
    string = f.readlines()
    print([k for k,v in Counter(string).items() if v == 2])

如果要重复所有行(行重复两次或更多次)

with open('log.txt') as f:
    string = f.readlines()
    print([k for k,v in Counter(string).items() if v > 1])

您正在打印所有字符串,而不仅仅是重复的字符串,要仅打印重复两次的字符串,您可以打印计数为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) 

你可以用^{}也就是说

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

这将打印计数最高的计数器条目

相关问题 更多 >