【问题标题】:Search for number in a text file?在文本文件中搜索数字?
【发布时间】:2017-11-02 17:23:59
【问题描述】:

我尝试从我的日志文件中获取一个数字。这个数字出现在每个“当前商店使用情况是”之后。我怎样才能做到这一点?我可以使用re 模块吗?

日志文件中的行

2017-05-30 12:01:03,168 | WARN  | Store limit is 102400 mb (current store usage is 0 mb). The data directory: /opt/apache-activemq-5.12.0/bin/linux-x86-64/../../data only has 6887 mb of usable space - resetting to maximum available disk space: 6887 mb | org.apache.activemq.broker.BrokerService | WrapperSimpleAppMain

我的代码

def log_parser():
    palab2 = "WARN"
    logfile = open("/opt/apache-activemq-5.12.0/data/activemq.log", "r")
    contenlog = logfile.readlines()
    logfile.close()
    for ligne in contenlog:
        if palab2 in ligne:
            print ("Probleme : " + ligne)

【问题讨论】:

  • 不要使用readlines 读取整个文件。您可以遍历每一行。是的,您可以使用re

标签: python regex text-processing text-parsing


【解决方案1】:

是的,您可以使用re 模块来大大简化此操作。并且 +1 到 @Eric Duminil 建议不要一次读取整个文件。

import re

def log_parser():
    palab2 = "WARN"
    logfile = "/opt/apache-activemq-5.12.0/data/activemq.log"

    with open(logfile, 'r') as contenlog:
        for ligne in contenlog:
            if re.findall(palab2, ligne):
                print ("Probleme : " + ligne)
                break

【讨论】:

    【解决方案2】:

    这对你有用:

    import re
    ligne  = '2017-05-30 12:01:03,168 | WARN | Store limit is 102400 mb (current store usage is 0 mb). The data directory: /opt/apache-activemq-5.12.0/bin/linux-x86-64/../../data only has 6887 mb of usable space - resetting to maximum available disk space: 6887 mb | org.apache.activemq.broker.BrokerService | WrapperSimpleAppMain'
    print(re.search(r'current store usage is (\d+)', ligne).group(1))
    # this returns a 'string', you can convert it to 'int'
    

    输出:

    '0'
    

    编码愉快!!!

    【讨论】:

      【解决方案3】:

      试试这个:

      import re
      
      def log_parser():
          with open("/opt/apache-activemq-5.12.0/data/activemq.log", "r") as logfile:
              for line in logfile:
                  m = re.search(r"current store usage is (\d+)", line):
                      if m:
                          return m.group(1)
      
      print(log_parser())
      

      您没有指定是只想要第一次出现(我假设是这样)还是文件中的所有此类行。如果后者为真,只需将return更改为yield,然后像这样调用函数:print(list(log_parser()))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多