import json # python has a default parser
# assume this is your log message
log_line = '{"Ignoring entry" : {"Affected columns": [1, 3], "reason" : "some reason", "Details": {}}}'
data = json.loads(log_line)
print("Columns to ignore:", data["Ignoring entry"]["Affected columns"])
如果要使用当前格式,则必须使用str方法或re模块。你知道吗
例如,您可以这样做:
log_msg = "Ignoring entry, Affected columns [column1:column2], reason[some reason], Details[some entry details]"
def parse_log_line(log_line):
if log_line.startswith("Ignoring entry"):
log_data = {
for element in log_line.split(',')[1:]: # parse all elements but the header
key, value = element.partition('[')
if value[-1] != ']':
raise ValueError('Malformed Content. Expected %r to end with "]"' % element)
value = value[:-1]
log_data[key] = value
return log_data
raise ValueError('Unrecognized log line type')
如果您可以随意更改日志格式,那么使用公共数据格式是最简单的—我建议将JSON用于此类数据。它是结构化的,但足够轻量级,甚至可以从自定义bash脚本编写它。^{} module 允许您直接将其转换为本机python对象:
如果要使用当前格式,则必须使用
str
方法或re
模块。你知道吗例如,您可以这样做:
许多解析任务最好由^{} module 紧凑地处理。它允许您使用正则表达式。它们非常强大,但是如果你不习惯的话,很难维护。在您的情况下,以下操作将起作用:
重建工作如下:
,
一个逗号,用来分隔条目\s*
逗号后,下一个元素前的任意空格序列(.+?)
任何非空白字符(键,通过'()'
捕获)\s*
键和值之间的任意空格序列\[
文字[
(.+?)
下一个元素之前的最短的非空白字符序列(通过'()'
捕获的值)\]
文字]
符号
*
、+
和?
表示“任意”、“多个”和“尽可能少”。你知道吗相关问题 更多 >
编程相关推荐