首页 > 解决方案 > 有没有办法比较位于 json 中的两个列表的元素?

问题描述

我目前正在从日志中解析消息并将它们打印出来。在我解释我的问题之前,请参阅下面的程序。

    count = 0
    error_list = ["*SSH connection as gentan (using password) successful.*", "*Deployment State Updated to ATTEMPTING_CONNECTION*"]
    
    for i in data['deploymentStatus']['page']:
        count = count + 1
        regex = re.compile(error_list)
        if re.findall(regex, i['history']) is True:
            string = """
        ========================
            TARGET # %s
        ========================
        [+] IP      => %s
        [+] HISTORY => %s""" % (count, i['address'], i['history'])
            print(string)

这是i['history']的代码。

i['history] = ["13/04/2021 05:42:59:589Z: Attempting connection via ssh as gentan.", "13/04/2021 05:42:59:589Z: Deployment State Updated to ATTEMPTING_CONNECTION"]

现在最后我想要的是,我希望 if 语句只打印在error_listi['history']中相互匹配的日志

在我的情况下它不匹配的原因是因为它以日期和时间开头,python中有没有办法解析出来并只比较字符串?

我将不胜感激任何帮助。我也可以发布完整的data['deploymentStatus']['page'] json 文件,但它太长了,无法在此处发布12k+ 行

标签: pythonlistre

解决方案


您不需要使用正则表达式。只需使用in运算符来测试其中一个字符串error_list是否在历史字符串中。

error_list = ["SSH connection as gentan (using password) successful", "Deployment State Updated to ATTEMPTING_CONNECTION"]

for i in data['deploymentStatus']['page']:
    if any(error in i['history'] for error in error_list):
        print("""
        ========================
            TARGET # %s
        ========================
        [+] IP      => %s
        [+] HISTORY => %s""" % (count, i['address'], i['history']))

count = len(data['deploymentStatus']['page']) # no need to calculate this in the loop

推荐阅读