【发布时间】:2019-08-12 12:20:15
【问题描述】:
我有一个带有换行符的日志文件
示例文件:
2019-02-12T00:01:03.428+01:00 [Error] ErrorCode {My error: "A"} - - - 00000000-0000-0000-6936-008007000000
2019-02-12T00:01:03.428+01:00 [Error] ErrorCode {My error: "A"} - - - 00000000-0000-0000-6936-008007000000
2019-02-12T00:03:23.944+01:00 [Information] A validation warning occurred: [[]] while running a file,
--- End of stack trace ---
FileNotFoundError
--- End of stack trace from previous location where exception was thrown ---
System Error
我想将数据分成三列,即时间戳、类型代码,以显示事件是错误、警告还是信息,然后是消息。
我为此使用了拆分功能:
currentDict = {"date":line.split("] ")[0].split(" [")[0],
"type":line.split("] ")[0].split(" [")[1],"text":line.split(" ]")[0].split("] ")[1]}
要拆分给定列中的数据,它可以正常工作,但如果我有如下所示的条目,则会出错
2019-02-12T00:03:23.944+01:00 [Information] A validation warning occurred: [[]] while running a file,
--- End of stack trace ---
FileNotFoundError
--- End of stack trace from previous location where exception was thrown ---
System Error
第二种方法是使用正则表达式
with open(name, "r") as f:
for lines in f:
data_matcher = re.findall("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}.\\d{1,3}[+]?\\d{1,2}:\\d{1,2}",
lines)
使用这个我只能提取时间戳,但不知道如何提取字段的下一个。
【问题讨论】:
-
好吧,怎么说最好:使用空格作为字段分隔符和字段内部而不被同时引用将是解析这个的一个严重问题。您可以尝试有限的左拆分,然后是有限的右拆分,从两侧靠近文本字段。