【发布时间】:2021-09-22 02:12:34
【问题描述】:
给定一个日志字符串数组:
log = [
'[WARNING] 403 Forbidden: No token in request parameters',
'[ERROR] 500 Server Error: int is not subscription',
'[INFO] 200 OK: Login Successful',
'[INFO] 200 OK: User sent a message',
'[ERROR] 500 Server Error: int is not subscription'
]
我正在尝试在 python 中更好地使用字典,并希望遍历这个数组并打印出如下内容:
{'WARNING': {'403': {'Forbidden': {'No token in request parameters': 1}}},
'ERROR': {'500': {'Server Error': {'int is not subscriptable': 2}}},
'INFO': {'200': {'OK': {'Login Successful': 1, 'User sent a message': 1}}}}
本质上,我想返回一个字典,其中包含上述格式的日志记录统计信息。 我开始写我的方法并写到这里:
def logInfo(logs):
dct = {}
for log in logs:
log = log.strip().split()
if log[2] == "Server":
log[2] = "Server Error:"
log.remove(log[3])
#print(log)
joined = " ".join(log[3:])
if log[0] not in dct:
log[0] = log[0].strip('[').strip(']')
dct[log[0]] = {}
if log[1] not in dct[log[0]]:
dct[log[0]][log[1]] = {}
if log[2] not in dct[log[0]][log[1]]:
dct[log[0]][log[1]][log[2]] = {}
if joined not in dct:
dct[log[0]][log[1]][log[2]][joined] = 1
else:
dct[log[0]][log[1]][log[2]][joined] += 1
else:
dct[joined].append(joined)
print(dct)
改为打印:
{'WARNING': {'403': {'Forbidden:': {'No token in request parameters': 1}}}, 'ERROR': {'500': {'Server Error:': {'int is not subscription': 1}}}, 'INFO': {'200': {'OK:': {'User sent a message': 1}}}}
该方法本身也很长,任何人都可以帮助或提示我一种更熟练的处理方法吗?
【问题讨论】:
标签: python dictionary multidimensional-array