簡體   English   中英

在defaultdict(list)python中計數

[英]count in defaultdict(list) python

沒有你的幫助,我無法讓它工作。 我想基於devicename過濾一些系統日志消息。 輸出應該如下所示。

Device1: 1x failure1,50 x failure2, 20x failure3
Device3: 10 x failure1,5 x failure2, 2x failure3

碼:

frequencies = defaultdict(list)

word = ['syslog1error1','syslog1error2','syslog1error3']

def findpattern():
    for line in syslog:
            if re.search(r"regexforhostname",line):
                hostname= line.strip()[16:27]
                for failure in word:
                    if failure in line:     
                    frequencies[hostname].append(failure)

x = findpattern()

print frequencies

輸出看起來像

'Devicename':'syslog1error1', 'syslog1error1', 'syslog1error2', 'syslog1error3'

我想計算列表中的雙重條目。 但我無法使用導入集合運行它(計數器)

請幫忙。

使用collections.Counter() (如果您使用的是Python版本<2.7,請參閱Collections模塊中的Counter ):

from collections import Counter, defaultdict

def findpattern():
    frequencies = defaultdict(Counter)

    for line in syslog:
        if re.search(r"regexforhostname",line):
            hostname= line.strip()[16:27]
            frequencies[hostname].update(f for f in word if f in line)

    return frequencies

result = findpattern()
for device, frequencies in result.iteritems():
    print '{}: {}'.format(
        device, 
        ', '.join(['{}x {}'.format(c, f) for f, c in frequencies.most_common()]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM