python:拆分一条线

时间:2017-08-09 13:18:49

标签: python python-2.7

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

systemMonitor:[YYYY-MM-DD HH:MM:SS,###] [STATUS] node-id:错误的一些错误:有关它的更多信息,很多空格

所以我们有4个部分都是相同的:systemMonitor,日期和状态(错误,信息,成功等...)节点ID
在那之后,我们得到它自己的错误,它可以从一个错误到另一个错误

我想解析这一行,以便我得到一个字典:

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

我试过用白色空格拆分它,没用 目前,我很难编码:在第[14]行,我们得到了另一个索引的systemMonitor部分,我得到了日期等等。

有没有更好的方法来实现它?

示例行:

SystemMonitor:[2017-08-07 10:05:00,333] [ERROR] 12432:缺少端口号302 SystemMonitor:[2017-08-07 10:05:00,333] [ERROR] 13332:无法联系主持人

3 个答案:

答案 0 :(得分:1)

尝试使用正则表达式。这是一个例子,可以(并且应该)进行改进,但它会让你开始:

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

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

答案 1 :(得分:0)

这会是一个有用的解决方案吗?用你拥有的东西!

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]

答案 2 :(得分:0)

你可以试试这个:

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'}]