Grabbing IP addresses from a file and counting the occurences
file, ip, python, python-2.7
Solution
`re.findall()` will return a list, so try anther loop with append:
#!/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
Problem
I am quite new to python and got stuck while doing a school assignment. 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. I keep getting an error: 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 you!