Jingdong dihedral programming problem (using python in a file)

Jingdong dihedral programming problem (using python in a file)

Topics requirements:
1. Create a large file ips.txt, requires 1200 row, each row is random ip 172.25.254.0/24 segments;
2. Read ips.txt statistics file in the file before ip 10 ip discharge frequency of occurrence;

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'))

Output:
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

Published 59 original articles · won praise 6 · views 1307

Guess you like

Origin blog.csdn.net/weixin_45775963/article/details/104113510