Capturing IP addresses from a file and counting events

I'm new to python and stuck doing school assignment. I have to grab the IP addresses from the file, and then count the number of times each IP appears and print the result.

I keep getting the error message: Unhashable Type: '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!

+4
source share
2 answers

re.findall() will return a list, so try a vacuum cleaner loop with the addition of:

#!/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 are the lines of file data:

123.0.9.1
fjdakl
jfkal 23.2.2.9

function return None

+3
source

. 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))
+1

All Articles