从具有时间和错误的文件中获取分组字典列表,然后在python中绘制时间差

时间:2016-10-04 18:32:55

标签: python numpy matplotlib plot

我有以下文件:

Date;Time;Task;Error_Line;Error_Message
03-13-15;08:2123:10;C:LOGINMAN;01073;Web Login Successful from IP Address xxx.xxx.x.xx
03-13-15;05:23:1235;B:VDOM;0906123;Port 123 Device 1012300 Remote 1 1012301 Link Up RP2009
03-13-15;05:23:123123;A:VCOM;0906123;Port 123 Device 1012300 Remote 1 1012301 Link Up RP2009
03-13-15;05:23:123123;B:VDOM;1312325;Port 123 Device 1012300 Remote 1 1012301 Receive Time Error: 2123666 23270 1396 69
03-13-15;05:23:1233;B:VDOM;13372;Port 123 Device 1012300 Remote 1 1012301 Send Time Error: 123123123 1888 1123123123 69
03-13-15;05:23:1233;A:VCOM;1312325;Port 123 Device 1012300 Remote 1 1012301 Receive Time Error: 2123666 23270 1396 69
03-13-15;05:23:1233;A:VCOM;13372;Port 123 Device 1012300 Remote 1 1012301 Send Time Error: 123123123 1888 1123123123 69
03-13-15;05:21:56;B:VDOM;07270;Port 123 Device 1012300 Remote 1 1012301 AT Timer Expired
03-13-15;05:21:56;A:VCOM;07270;Port 123 Device 1012300 Remote 1 1012301 AT Timer Expired

所需的输出应该是这样的:

D = {'Error_line1': [Time1,Time2,...],'Error_Line2' = [Time1,Time2,..],...}

我一直在寻找根据Error_Line绘制不同时间之间的差异。我文件中的Error_Line发生在不同的时间。我希望根据Error_Line进行组时间。我不知道这是否适合绘制时间。

2 个答案:

答案 0 :(得分:1)

至于按行号分组,这应该可以解决问题:

import csv
D = {}
with open('logfile') as f:
    reader = csv.DictReader(f, delimiter=';')
    for row in reader:
        el = row['Error_Line']
        if el not in D:
            D[el] = []  # Initiate an empty list
        D[el].append(row['Time'])

答案 1 :(得分:1)

我不会触及绘图,因为有多种显示数据的方式,我不知道你在寻找什么样的风格。您想为每个Error_Line分别创建图表吗?每个Error_Line的数据点都在一个图表上表示?比较时间和错误的其他一些方法(例如,每个Error_Line的时间相对于彼此绘制的平均值,方差,yadda yadda)?

然而,将该信息放入dict中将涉及获取每一行,用分号作为分隔符将其拆分,然后挑选出你想要的碎片。就个人而言,我这样做:

from collections import defaultdict
ourdata = defaultdict(list)
with open('stackoverflow.txt') as ourfile:
    for row in ourfile:
        datatoadd = row.split(';')[1:4:2]
        ourdata[datatoadd[1]].append(datatoadd[0])

就那些时间戳而言,它们目前是字符串。您还需要将它们(在append语句中一次性完成)转换为您需要的数据类型(例如numpy的datetimes允许算术)。

有关此处发生了什么的更多信息,请参阅:defaultdictwithstr.split()extended slice notation