gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:01:35 25 4
gpt4 key购买 nike

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 语句,无法编译,并且错误地使用了正则表达式结果。您的正则表达式不必要地复杂(例如,需要尾随空格字符)。

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

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

关于python - 在 python 中已排序的 ("Error"字典的零索引位置插入列名称为 "Count", "error"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61800569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com