【问题标题】:Is there a way to compare the elements of two lists residing in a json?有没有办法比较位于 json 中的两个列表的元素?
【发布时间】:2021-04-30 22:59:53
【问题描述】:

我目前正在从日志中解析消息并将其打印出来。在我解释我的问题之前,请先查看下面的程序。

    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_list 和 i['history']

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

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

【问题讨论】:

  • “有什么办法吗”对于 Stack Overflow 来说不是问题。由于您使用的是几乎没有图灵机的通用计算机,因此答案几乎总是“是”。后续问题“我该怎么做?”对于 Stack Overflow 来说过于宽泛。请从intro tour 重复on topic 和how to ask。
  • 您已经确定了您需要的点:字符串处理以识别和删除您不想要的部分,然后与其他一些参考字符串进行比较。重复相关教程,编写代码,并(如果遇到问题)提供预期的minimal, reproducible example (MRE)。
  • re.compile() 的参数必须是单个字符串,而不是列表。
  • re.findall(regex, i['history']) 返回一个匹配列表,所以is True 永远不会成功。
  • 正则表达式开头的 * 无效。它必须以模式开头,它匹配该模式的任何序列。

标签: python list python-re


【解决方案1】:

您不需要使用正则表达式。只需使用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

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多