我对python很陌生,在做学校作业时遇到了麻烦。我应该从一个文件中获取IP地址,然后计算每个IP出现的次数,并打印出结果。
我一直收到一个错误:unhable 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')
谢谢您!
最佳答案
re.findall()
将返回一个列表,因此使用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')
以下是文件数据行:
123.0.9.1
fjdakl
jfkal 23.2.2.9
函数不返回