我有一个字典列表。
data = [
{'@timestamp': '2018-10-29T05:57:12.722Z','messages': '[FANATIC] - - Session id kajdhrg7uhdfvbshfgadf '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': '[FANATIC] - - Exception Lorem Ipsum Rebolt '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'JHUSHDVCHBASJd'},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'asdfawerg cdv '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'fya7 5 Lorem Ipsum Rebolt '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'zxcgwrt asdfg w4e6354gdf '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'zcfb26 eqrgsfdb syh2456ytdfg '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'we57hb354gf '},
{'@timestamp': '2018-10-29T06:59:12.722Z','messages': '[FANATIC] - - sdfsum Rebolt '},
{'@timestamp': '2018-10-29T06:59:12.722Z','messages': '[FANATIC] - - sdfsum Rebolt '}
]
这是一个日志模式。但错误日志新行没有 [FANATIC]
,它应该在单行或单条消息中。
有没有办法将这些内容放入新字典中,并仅包含错误的共轭消息?
for i in data:
if "[FANATIC]" in i['messages'] and "exception" in i['messages']:
print(i)
我是否可以在新字典中捕获“行间”?
编辑:
我想要的类似于下面...:
data = [
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': '[FANATIC] - - Exception Lorem Ipsum Rebolt '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'JHUSHDVCHBASJd'},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'asdfawerg cdv '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'fya7 5 Lorem Ipsum Rebolt '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'zxcgwrt asdfg w4e6354gdf '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'zcfb26 eqrgsfdb syh2456ytdfg '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': 'we57hb354gf '},
{'@timestamp': '2018-10-29T06:58:12.722Z', 'messages': [
'[FANATIC] - - Exception Lorem Ipsum Rebolt',
'JHUSHDVCHBASJd',
'asdfawerg cdv ',
'fya7 5 Lorem Ipsum Rebolt ',
'zxcgwrt asdfg w4e6354gdf ',
'we57hb354gf '
]
},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': '[FANATIC] - - sdfsum Rebolt '},
{'@timestamp': '2018-10-29T06:58:12.722Z','messages': '[FANATIC] - - sdfsum Rebolt '}
]
最佳答案
只需使用理解来过滤您的列表:
res = [x for x in data if x["messages"].startswith("[FANATIC]")]
或者对于这两项检查:
res2 = [x for x in data if all(s in x["messages"] for s in ("Exception", "FANATIC"))]
要获取“行间”的内容,您可以从左侧和右侧剥离:
def StriptStuff(s):
return s.lstrip("[FANATIC] -").rstrip("- Exception Lorem Ipsum Rebolt ")
res2 = [StriptStuff(x["messages"]) for x in data if all(s in x["messages"] for s in ("Exception", "FANATIC"))]
但是对于更复杂的东西,正则表达式
会更好。
这里有一个live example
关于Python 字典列表并根据特定情况创建另一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53057836/