python分割一行

2024-03-29 08:01:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个日志文件,其中每行都遵循以下格式:

systemMonitor:[yyyyy-MM-DD HH:MM:SS,####][STATUS]节点id:某些错误某些错误描述:有关它的详细信息,大量空白

因此,我们有4个部分是完全相同的:系统监视器、日期和状态(错误、信息、成功等…)节点ID
在那之后,我们得到它自己的错误,它可以不同于一个错误到另一个错误

我想分析这行,这样我就可以得到一个字典,其中:

main: systemMonitor,
date: the date,
status: the status,
error_msg: the error msg,

我尝试过用空格分隔,但没有成功。
目前,我正在硬编码它:在第[14]行,我们在另一个索引中得到systemMonitor部分,我得到日期等等。你知道吗

有没有更好的方法来实现它?你知道吗

示例行:

SystemMonitor:[2017-08-07 10:05:00333][错误]12432:缺少端口号302 系统监视器:[2017-08-07 10:05:00333][错误]13332:无法到达主机


Tags: 文件thedate节点系统格式status错误
3条回答

你可以试试这个:

import re
output = ["SystemMonitor: [2017-08-07 10:05:00,333] [ERROR] 12432: missing port number 302",  "SystemMonitor: [2017-08-07 10:05:00,333] [ERROR] 13332: cant reach host"]

headers = ["main", "date", "status", "error_msg"]

new_data = [re.split("\s(?=\[)", i) for i in output]

new_data = [i[:-1]+i[-1].split(":") for i in new_data]

final_error_messages = [{a:b for a, b in zip(headers, i)} for i in new_data]

输出包含包含包含所需数据的词典列表:

[{'date': '[2017-08-07 10:05:00,333]', 'status': '[ERROR] 12432', 'main': 'SystemMonitor:', 'error_msg': ' missing port number 302'}, {'date': '[2017-08-07 10:05:00,333]', 'status': '[ERROR] 13332', 'main': 'SystemMonitor:', 'error_msg': ' cant reach host'}]

这是一个有用的解决方案吗?用你所有的!你知道吗

lne='SystemMonitor:[2017-08-07 10:05:00,333] [ERROR] 12432: missing portnumber 302'

date = lne[15:25] # I really see no problem in hard coding here
status = lne.split('[')[-1].split(']')[0] 
error_msg = lne.split(':')[-1]

尝试使用正则表达式。下面是一个可以(也应该)改进的示例,但它会让您开始:

import re
m=re.match(r"systemMonitor: \[(?P<date>.+)\] \[(?P<status>\w+)\] (?P<node_id>\d+): (?P<error>.*)\s*", line)

然后可以使用m.group("date")等获得值

相关问题 更多 >