欢迎来到Felix的博客

雨恨云愁,江南依旧称佳丽。水村渔市。一缕孤烟细。天际征鸿,遥认行如缀。平生事。此时凝睇。谁会凭阑意
返回顶部

python编程练习---打印出日志中以小时为单位,出现不同Exception的错误的次数

今天在网易二面的时候,面试官出了一道个人感觉很有意思的面试题,现在分享给大家,看大家有没有什么好的其他的思路

问题:给定一个test.txt的日志文件,文件的内容如下:
20201011 103232 Exception: Null Pointer
20201011 101433 Exception: Null Pointer
20201012 093232 Exception: Null Pointer
20201013 141433 Exception: Type error
20201013 103232 Exception: testerror
20201013 101433 sdfsdfsdf
20201014 103232 wefwef
20201015 101433 Exception: Null Pointer

要求以小时为节点,打印出每个小时内错误类型出现的次数,格式如下:
20201011 10 Exception: Null Pointer 2
20201013 10 Exception: PPOO Pointer 1

编码思路如下:

# -*- coding: utf-8 -*-
__author__ = 'felix'
with open("./test.txt", 'r') as f:
    line_dict = {}      #定义一个字典
    for line in f:
        line = line.strip()    #去除尾部换行符、空格
        if 'Exception' not in line:       #判断该行是否包含Exception
            continue          #不包含就继续读下一行
        else:
            line_list = line.split('Exception:')         #['20201011 103232', ' Null Pointer']
            k = line_list[0][:11]       #'20201011 10'
            val = line_list[1]          #' Null Pointer'
            if k + val not in line_dict:
                line_dict[k + val] = 1     # '20201011 10 Null Pointer' : 1
            else:
                line_dict[k + val] += 1
    for k, v in line_dict.items():         #遍历字典
        print(k[:11] + ' Exception:' + k[11:] + ' ' + str(v))

大家有什么其他好的思路吗?

posted @ 2021-01-07 19:32  felixtester  阅读(214)  评论(0)    收藏  举报