2017-08-02 50 views
0

我需要計算給定數量的os文本模式出現在日誌文件中的次數,並將其存儲在字典中。在循環中遞增詞典:

我的問題是,我的代碼是計算文件的所有條目到每種文本模式。

日誌文件看起來像這樣:

我做錯了什麼?

>Feb 1 00:00:02 bridge kernel: INBOUND TCP: IN=br0 PHYSIN=eth0 OUT=br0 >PHYSOUT=eth1 SRC=XXX.XXX.XXX.XXX DST=XXX.XXX.XXX.XXX LEN=40 TOS=0x00 >PREC=0x00 TTL=110 ID=12973 PROTO=TCP SPT=220 DPT=6129 WINDOW=16384 RES=0x00 >SYN URGP=0 
>Feb 1 00:00:02 bridge kernel: INBOUND TCP: IN=br0 PHYSIN=eth0 OUT=br0 >PHYSOUT=eth1 SRC=XXX.XXX.XXX.XXX DST=XXX.XXX.XXX.XXX LEN=40 TOS=0x00 >PREC=0x00 TTL=113 ID=27095 PROTO=TCP SPT=220 DPT=6129 WINDOW=16384 RES=0x00 >SYN URGP=0 

我的代碼是這樣的時刻:

#!//usr/bin/python3 

import sys 
import os 
import re 
from collections import defaultdict 

    tipos={} 
    p= re.compile ('bridge kernel:.*:') 
    with open (sys.argv[1], 'r') as f: 
     for line in f: 
      match = p.search(line) 
      if match: 
       taux=(line.split(":") [3]) 
       tipos[taux]=1 
    print (tipos) 

的代碼不給一個錯誤,但所有主要有保存價值。

我讀過關於defaultdictCounters,但無法讓他們工作。

請幫助我。

+0

都等於1? – jacoblaw

+0

也許你的意思是'ipos [taux] + = 1'? – lpiner

回答

1

至於你的代碼的版本,你永遠不增加計數的數量因爲他們應該都是一個人。是的,defaultdicts會有所幫助,因爲它們自動實例缺少字典項與您傳遞類型,通常defaultdict計數模式如下:

a = defaultdict(int) 
a['asdf'] += 1 
# a['asdf'] will now be 1, since it updates from 0 

編輯:包括@讓FrançoisFabre評論,我想點出collections模塊帶有一個專門設計用於計算任何可散列對象的對象 - Counter。從外觀上看,它依賴於大部分相同的後端,所以性能應該是相似的,但它帶有一些很好的額外功能(如most_common(number_of_most_common_elements)方法)。這可以像defaultdict一樣使用,但沒有專用(int)參數: 。

a = Counter() 
a['asdf'] += 1 
# a['asdf'] will now be 1, since it updates from 0 

在一般情況下,通過將對應於默認值的每個參數這意味着,你可以做以下還有:

a = defaultdict(int) 
print(a['asdf']) # will print 0 
a = defaultdict(float) 
print(a['asdf']) # will print 0.0 
a = defaultdict(list) 
print(a['asdf']) # will print [], and is particularly useful if you want a dict of lists, since you don't need to check whether your key already exists in the dict 

爲你的代碼,這意味着你想要的:

tipos=defaultdict(int) 
p= re.compile ('bridge kernel:.*:') 
with open (sys.argv[1], 'r') as f: 
    for line in f: 
     match = p.search(line) 
     if match: 
      taux=(line.split(":") [3]) 
      tipos[taux]+=1 
print (tipos) 
+0

'collections.Counter'更能算出元素。 –

+0

@ Jean-FrançoisFabre謝謝 - 很好的指針。我更新了答案。 – cleros

0

您想使用defaultdict:

tipos = defaultdict(int) 
p= re.compile ('bridge kernel:.*:') 
with open (sys.argv[1], 'r') as f: 
    for line in f: 
     match = p.search(line) 
     if match: 
      taux=(line.split(":") [3]) 
      tipos[taux] += 1 
print (tipos) 

你擁有了它進口的有,但你不使用它