题目要求:
- 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
- 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import random
def create_ip_file(filename):
ips = ['172.25.254.'+str(i) for i in range(1,255)]
print(ips)
with open(filename,'a+')as f:
for count in range(1200):
print(random.sample(ips,1))
f.write(random.sample(ips,1)[0])
create_ip_file('ips.txt')
def sorted_ip(filename,count=10):
ips_dict=dict()
with open(filename) as f:
for ip in f:
if ip in ips_dict:
ips_dict[ip]+=1
else:
ips_dict[ip]=1
sorted_ip=sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:count]
return sorted_ip
print(sorted_ip('ips.txt'))
结果是:
['172.25.254.132']
['172.25.254.150']
['172.25.254.107']
['172.25.254.186']
['172.25.254.59']
['172.25.254.47']
['172.25.254.120']
['172.25.254.246']
['172.25.254.81']
[('172.25.254.185\n', 18), ('172.25.254.229\n', 18), ('172.25.254.21\n', 17), ('172.25.254.99\n', 17), ('172.25.254.100\n', 16), ('172.25.254.61\n', 16), ('172.25.254.228\n', 16), ('172.25.254.117\n', 16), ('172.25.254.60\n', 16), ('172.25.254.221\n', 15)]