【问题标题】:Python how to grep two keywords from a sting in a text file and append into two stringsPython如何从文本文件中的字符串中提取两个关键字并附加到两个字符串中
【发布时间】:2022-10-06 01:36:13
【问题描述】:
DELIVERED,machine01,2022-01-20T12:57:06,033,Email [Test1] is delivered by [192.168.0.2]

以上是文本文件中的内容。我使用了 split(\",\") 方法,但我不知道如何使它如下工作。有人能帮忙吗?

\'DELIVERED\', \'machine01\', \'2022-01-20T12:57:06\', \'033\', \'Test1\', \'192.168.0.2\'
with open(\'log_file.log\', \'r\') as f:
    for line in f.readlines():
        sep = line.split(\",\")
        print(sep)

    标签: python-3.x


    【解决方案1】:
    text = "DELIVERED,machine01,2022-01-20T12:57:06,033,Email [Test1] is delivered by [192.168.0.2]"
    result = []
    
    for part in text.split(','): # loops the parts of text separated by ","
        result.append(part) # appends this parts into a list
    
    print(result) # prints this list:
    ['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Email [Test1] is delivered by [192.168.0.2]']
    
    
    
    # or you can do all the same work in just 1 line of code!
    result = [part for part in text.split(',')]
    
    print(result)
    ['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Email [Test1] is delivered by [192.168.0.2]']
    

    【讨论】:

      【解决方案2】:

      使用, 拆分后,您需要使用正则表达式在最终字符串中查找[] 的内容。由于您在多行中执行此操作,我们将每个列表收集在一个变量 (fields) 中,然后在最后打印此列表列表:

      import re
      
      fields = []
      with open('log_file.log', 'r') as f:
          for line in f.readlines():
              sep = line.split(",")
              # Get the last item in the list
              last = sep.pop()
              # Find the values in [] in last
              extras = re.findall(r'\[(.*?)\]', last)
              # Add these values back onto sep
              sep.extend(extras)
              fields.append(sep)
      
      print(fields)
      

      log_file.log:

      DELIVERED,machine01,2022-01-20T12:57:06,033,Email [Test1] is delivered by [192.168.0.2]
      DELIVERED,machine02,2022-01-20T12:58:06,034,Email [Test2] is delivered by [192.168.0.3]
      

      结果:

      [['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Test1', '192.168.0.2'], ['DELIVERED', 'machine02', '2022-01-20T12:58:06', '034', 'Test2', '192.168.0.3']]
      

      【讨论】:

      • 谢谢。我试过你的代码,输出是[['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Test1'], ['DELIVERED', 'machine02', '2022-01-20T12:57:06', '033', 'Test2'],.....最后一串IP没有添加,我怎样才能得到如下输出? ['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Test1', '192.168.0.2'] ['DELIVERED', 'machine02', '2022-01-20T12:57:06', '033', 'Test2', '192.168.0.3']
      • 我已经修复了代码,现在添加了这两个字段。
      猜你喜欢
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多