【python】logファイルを解析し、出現回数上位3のipを取得する


#line format: 2019-09-27 19:00:00 file.cpp:12345 12.12.12.12
def getIp(line):
    """
    """
    ip = line.split(' ')[-1][0:-1]
    return ip
    
def process_ip_info(dic):
    """
    """
    ip_list = []
    count = 0
    for one in dic:
        ip_list.append(one[0]) 
        count = count + 1
        if count == 3:
            return ip_list

def process(lines):
    """
    """
    dic = {}

    for line in lines:
        ip = getIp(line)
        if not ip:
            continue
        else:
            if dic.has_key(ip):
                dic[ip] = dic[ip] + 1    
            else:
                dic[ip] = 1
    dic = sorted(dic.items(),key=lambda x:x[1], reverse=True)
    return process_ip_info(dic)

def run(file_name):
    """
    """
    try:
        h_handle = open(file_name, 'r')
        lines = h_handle.readlines()
        ip_list = process(lines) 
        print("the top 3 ip in log is %s" % ip_list)
    except Exception as ex:
        print("some errors[%s] happend" % ex)
    finally:
        if h_handle:
            h_handle.close()

if __name__ == "__main__":
    file_name = "./log.file"
    run(file_name)