2017-08-02 71 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) 

你拥有了它进口的有,但你不使用它