gpt4 book ai didi

python - 从文件中获取 IP 地址并计算出现次数

转载 作者:太空狗 更新时间:2023-10-30 03:00:34 27 4
gpt4 key购买 nike

我是 python 的新手,在做学校作业时被卡住了。我应该从文件中获取 IP 地址,然后计算每个 IP 出现的次数并打印出结果。

我一直收到错误:Unhashable 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() 将返回一个列表,因此尝试使用附加的花药循环:

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

函数返回无

关于python - 从文件中获取 IP 地址并计算出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28694992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com