【问题标题】:How to extract more than 20 duplicate IP addresses from a text file如何从文本文件中提取 20 多个重复的 IP 地址
【发布时间】:2019-12-30 12:25:53
【问题描述】:

我有一个 .txt 事件列表,我需要制作一个脚本来比较列表中的 IP,如果这些 IP 在不同的行中出现超过 15 次,则打印它在其中看到的行,那些

.txt 数据如下所示:

11/08/2019 07:47    192.168.14.14   tcp/20542   tcp/23  192.168.175.141
11/08/2019 07:55    192.168.98.105  tcp/38155   tcp/5555    192.168.170.188
11/08/2019 08:17    192.168.227.10  tcp/2739    tcp/8080    192.168.162.230
11/08/2019 08:32    192.168.74.26   tcp/52243   tcp/5555    192.168.187.234
11/08/2019 08:14    192.168.74.26   tcp/58019   tcp/5555    192.168.176.132
11/08/2019 08:14    192.168.74.26   tcp/58019   tcp/5555    192.168.176.132
11/08/2019 08:14    192.168.74.26   tcp/58019   tcp/5555    192.168.176.132

我该怎么做?

from collections import Counter

    with open('3.txt') as file:
        c=Counter(c.strip().lower() for c in file if c.strip())
            if c[line[17:31]]>20:
                print (line)

如果 IP 在行中出现超过 20 次,结果应该是这样的:

11/08/2019 07:55    192.168.98.105  tcp/38155   tcp/5555    192.168.170.188

【问题讨论】:

    标签: python-3.x list ip extract


    【解决方案1】:

    这是使用collections.defaultdict 的一种方法。

    例如:

    from collections import defaultdict
    
    check_val = defaultdict(int)
    with open('3.txt') as file:
        for line in file:
            line = line.strip().split()
            if check_val[line[-1]] > 15:
                print(line)
            else:
                check_val[line[-1]] += 1
    

    【讨论】:

    • 是的,这正是我想要的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2023-03-16
    相关资源
    最近更新 更多