【问题标题】:Grabbing IP addresses from a file and counting the occurences从文件中获取 IP 地址并计算出现次数
【发布时间】:2015-04-26 00:41:07
【问题描述】:

我对 python 很陌生,在做学校作业时被卡住了。我应该从文件中获取 IP 地址,然后计算每个 IP 出现的次数并打印出结果。

我不断收到错误消息:Unhashable Type: 'list'

代码如下:

#!/usr/bin/python
import re

def grab_ip(file):
    ips = []
    occurence = {}
    with open (file) as file:
        for ip in file:
            ips.append(re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', ip))
        for ipaddr in ips:
            if ipaddr in occurence:
                occurence[ipaddr] = occurence[ipaddr] + 1
            else:
                occurence[ipaddr] = 1
    for key, value in occurence.iteritems():
        print key, value
    return None
print grab_ip('FILE_WITH_IPS.txt')

谢谢!

【问题讨论】:

    标签: python file python-2.7 ip


    【解决方案1】:

    re.findall() 将返回一个列表,因此请尝试使用附加循环:

    #!/usr/bin/python
    import re
    
    def grab_ip(file):
        ips = []
        occurence = {}
        with open (file) as file:
            for ip in file:
                ip_data=re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',ip)
                for i in ip_data:
                    ips.append(i)
            for ipaddr in ips:
                if ipaddr in occurence:
                    occurence[ipaddr] = occurence[ipaddr] + 1
                else:
                    occurence[ipaddr] = 1
        for key, value in occurence.iteritems():
            print key, value
        return None
    print grab_ip('data')
    

    这里是文件数据行:

    123.0.9.1
    fjdakl
    jfkal 23.2.2.9
    

    函数返回无

    【讨论】:

      【解决方案2】:

      你完全在那里。只需使用extend 而不是append,因为findall 函数的输出必须是一个列表。因此,将一个列表附加到另一个列表将生成列表列表,这就是您收到错误 Unhashable Type: 'list' 的原因。

      ips.extend(re.findall(r'\b(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\b', ip))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-21
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 2012-09-01
        相关资源
        最近更新 更多