在python中使用字典来解析跟踪文件

时间:2017-10-19 22:39:20

标签: python arrays file parsing dictionary

我将使用python解析跟踪文件。我读了我文件的每一行,我想把这行添加到字典中。在我用space关键字分隔每一行并将每行的列添加到我的字典后,我打印结果。但问题是我的值与跟踪文件中的值不同。

换句话说,假设我的跟踪文件的第一行如下:

  • 0.1 1 2 cbr 1000 ------- 2 1.0 2.0 0 0

我的代码如下:

global dics
dics = []
count = 0
line_dic = {}
with codecs.open("trace.tr", "r", "UTF8") as inputFile:
    inputFile=inputFile.readlines()
for line in inputFile:
    item = []
    item = line.split(" ");
    line_dic['event'] = item[0]
    line_dic['time'] = item[1]
    line_dic['from_node'] = item[2]
    line_dic['to_node'] = item[3]
    line_dic['pkt_type'] = item[4]
    line_dic['pkt_size'] = item[5]
    line_dic['flags'] = item[6]
    line_dic['fid'] = item[7]
    line_dic['srcadd'] = item[8]
    line_dic['dstadd'] = item[9]
    line_dic['seqnum'] = item[10]
    line_dic['pkti'] = item[11]

    dics.append(line_dic)
    print dics

打印命令的结果是

[{'pkt_type': u'cbr', 'pkti': u'0\n', 'pkt_size': u'1000', 'seqnum': u'0', 'event': u'+', 'srcadd': u'1.0', 'flags': u'-------', 'fid': u'2', 'time': u'0.1', 'dstadd': u'2.0', 'to_node': u'2', 'from_node': u'1'}]

如您所见,根据我的知识,第一项必须是事件。但这是'pkt_type': u'cbr'

我不知道是什么问题?

1 个答案:

答案 0 :(得分:0)

我在代码中看到的一个问题是应该为每一行初始化line_dic(我在for循环中移动了line_dic = {})。如果没有它,您将覆盖前一行的字典。

dics = []
count = 0

with codecs.open("trace.tr", "r", "UTF8") as inputFile:
    inputFile=inputFile.readlines()
for line in inputFile:
    item = line.split(" ");

    line_dic = {}

    line_dic['event'] = item[0]
    line_dic['time'] = item[1]
    line_dic['from_node'] = item[2]
    line_dic['to_node'] = item[3]
    line_dic['pkt_type'] = item[4]
    line_dic['pkt_size'] = item[5]
    line_dic['flags'] = item[6]
    line_dic['fid'] = item[7]
    line_dic['srcadd'] = item[8]
    line_dic['dstadd'] = item[9]
    line_dic['seqnum'] = item[10]
    line_dic['pkti'] = item[11]

    dics.append(line_dic)
print dics

然后,调用dics[3]['event']应该没问题。您的dict不需要进行排序以进行该调用。