京东二面编程题(python中文件的使用)
题目要求:
1. 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
2. 读取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] + '\n')
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'))
输出结果: