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!
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
You're totally there. Just use extend
instead of append
because the output of findall
function must be a list. So appending a list to another list will produce list of list, that's why you got the error Unhashable Type: 'list'
.
ips.extend(re.findall(r'\b(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\b', ip))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.