我正試圖編寫一個程序,該程序需要一個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源,IP目的地和協議。
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()
試試'lst = records [0] .split(',')'。不要調用你的列表'list',因爲這是一個python內置的。但是目前,在分割它之前,您需要將1項目列表轉換爲其字符串表示形式。除此之外,我不確定你在問什麼。什麼是「田地」? – roganjosh
你會總是有包含三行數據的字符串嗎?還是僅僅是這個例子? – scnerd
有沒有什麼辦法可以爲每一行獲取不同的分隔符,比如'\ n'而不是'','? – scnerd