在 python 中已排序的 "error" 字典的零索引位置插入列名称为 ("Error", "Count")

Insert column names as ("Error", "Count") at the zero index position of the sorted "error" dictionary in python

error_count = {}
user_count = {}
with open(argv[1], 'r') as f:
    for line in f:
        result1 = re.search(r" ticky: ERROR ([\w ]*) ",line)
        if result1 is not None:
            if result1[1] not in error_count:
                error_count[result1[1]] = 0
            else:
                error_count[result1[1]] += 1
print (sorted(error_count.items(), key = operator.itemgetter(1), reverse=True))

我需要搜索日志文件并找到错误消息,然后在字典中将它们从发生次数最多到最少的顺序进行排序。我可以到达这里。

接下来,我需要在已排序的 "error_count" 字典的零索引位置插入列名作为 ("Error", "Count")。最后,我需要根据该词典创建一个 CSV 文件。我被困在这里了。哪位好心人帮我解决一下。

您发布的代码不完整并且有很多错误。它缺少所有 import 语句,无法编译,并且错误地使用了正则表达式结果。您的正则表达式不必要地复杂(例如,需要尾随 space 字符)。

这是一个完整的、经过测试的版本:

import sys
import re
from collections import defaultdict
import operator
import csv

error_count = defaultdict(str)
user_count = {}
with open(sys.argv[1], 'r') as f:
    for line in f:
        result1 = re.search(r" ticky: ERROR (.+)", line)
        if result1 is not None:
            msg = result1.group(1).rstrip()
            if msg not in error_count:
                error_count[msg] = 1
            else:
                error_count[msg] += 1

with open('error_count.csv', 'w') as cf:
    cw = csv.writer(cf)
    cw.writerow(['Error', 'Count'])
    for error in sorted(error_count.items(), key = operator.itemgetter(1), reverse=True):
        cw.writerow(error)

我运行它在这个输入文件上:

 ticky: INFO  this is not an error
 ticky: ERROR this is an error
 ticky: ERROR this is an error
 ticky: ERROR this is another error
 ticky: ERROR this is yet still an error
 ticky: DEBUG this is not an error either
 ticky: ERROR AAA this is an error
 ticky: ERROR AAA this is an error
 ticky: ERROR BBB this is an error
 ticky: ERROR CCC this is an error
 ticky: ERROR DDD this is an error
 ticky: ERROR CCC this is an error
 ticky: ERROR DDD this is an error
 ticky: ERROR DDD this is an error

输出文件 error_count.csv 为:

Error,Count
DDD this is an error,3
this is an error,2
AAA this is an error,2
CCC this is an error,2
this is another error,1
this is yet still an error,1
BBB this is an error,1