如何有效分离不同大小的数据输入?

How to effectively separate data inputs of varying sizes?

我正在尝试编写一个接受 pcap 文件的程序,通过应用程序 tshark 过滤数据包数据,并将数据输出到字典中,分离各个数据包。我在分离部分遇到问题。

这里基本上是我目前所拥有的:

#example data input
records = ["Jamie,20,12/09/1997,Henry,15,05/12/2002,Harriot,22,11/02/1995"]

dict = {}
list1 = str(records).split(',')
i = 0
#seperates list into sublists with length "3"
list1 = [list1[i:i + 3] for i in range(0, len(list1), 3)] 

#places the sublists into a dictionary
for i in range (0,len(fields)): #places the sublists into dictionary
    dict[i] = list1[i][0].split(',') + list1[i][1].split(',') + list1[i][2].split(',')

print(dict)

输出如下所示:

{0: ["['Jamie", '20', '12/09/1997'], 1: ['Henry', '15', '05/12/2002'], 2: ['Harriot', '22', "11/02/1995']"]}

我知道我的代码有缺陷且混乱。为了存储从每一行中获取更多数据,您需要手动将每个附加字段添加到字典中,同时必须更改拆分列表的位置。考虑到不同大小的输入,任何有关如何更好地自动化此过程的帮助,将不胜感激。如果我没有很好地解释我的问题,那就问吧。

编辑:这是我用来调用 tshark 的代码。前面代码的输入是 "out" 转换为字符串。前面例子中的姓名、年龄和出生日期分别代表ip source、ip destination和protocol。

filters = ["-e","ip.src"," -e ","ip.dst"," -e ","_ws.col.Protocol] #Specifies the metadeta to be extracted

tsharkCall = ["tshark.exe", "-r", inputpcap, "-T", "fields", filters]
tsharkProc = subprocess.Popen(tsharkCall, stdout=subprocess.PIPE)

out, err= tsharkProc.communicate()

考虑如下内容:

filters = ["ip.src","ip.dst","_ws.col.Protocol"] #Specifies the metadeta to be extracted
ex_base = 'tshark.exe -r {path} -Tfields {fields}'
ex = ex_base.format(path=myfile, fields=' '.join('-e ' + f for f in filters))
tsharkProc = subprocess.Popen(ex.split(), stdout=subprocess.PIPE, universal_newlines=True)

out, err= tsharkProc.communicate()

split_records = [line.split('\t') for line in out.split('\n')]
records = [dict(zip(filters, line)) for line in split_records]

# [{'ip.src': '127.0.0.1', 'ip.dst': '192.168.0.1', '_ws.col.Protocol': 'something'}, {...}, ...]

这假定您保留默认的输出定界符,即记录之间的换行符和字段之间的制表符。通过将您的字段数组压缩到您的输出记录中,您将自动扩展字典以适应您将新字段添加到该数组中。

注意你也可以使用 Pandas 所以优雅地解决这个问题,比如:

import pandas as pd
records = pd.Dataframe(split_records, columns=filters)

这将为您提供一个可以使用的数据帧结构,根据您的应用程序可能会有用。