简体   繁体   English

从文件中抓取IP地址并计算出现的次数

[英]Grabbing IP addresses from a file and counting the occurences

I am quite new to python and got stuck while doing a school assignment. 我对python很新,在完成学校作业时遇到困难。 I am supposed to grab IP addresses from a file and then count the amount of times each IP appears and print out the result. 我应该从文件中获取IP地址,然后计算每个IP出现的次数并打印出结果。

I keep getting an error: Unhashable Type: 'list' 我一直收到错误:不可用类型:'list'

Here is the code: 这是代码:

#!/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')

Thank you! 谢谢!

re.findall() will return a list, so try anther loop with append: re.findall()将返回一个列表,因此请尝试使用附加的anther循环:

#!/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')

here is file data lines: 这是文件数据行:

123.0.9.1
fjdakl
jfkal 23.2.2.9

the function return None 函数返回无

You're totally there. 你完全在那里。 Just use extend instead of append because the output of findall function must be a list. 只需使用extend而不是append因为findall函数的输出必须是一个列表。 So appending a list to another list will produce list of list, that's why you got the error Unhashable Type: 'list' . 因此,将列表附加到另一个列表将生成列表列表,这就是您收到错误Unhashable Type: 'list'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM