python - 在文本文件中搜索数字?

标签 python regex text-processing text-parsing

我尝试从我的日志文件中获取一个数字。这个数字出现在每个“当前商店使用情况是”之后。我怎样才能做到这一点?我可以使用 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)

最佳答案

是的,您可以使用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

关于python - 在文本文件中搜索数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44309614/

相关文章:

python - 为什么 find_packages(exclude=xxx) 在执行 setup.py sdist 时不起作用?

python - 使用前一行引用快速循环 Python 数据框

c - 从 xml 响应中提取 url

比较两个没有 CR LF 的字符数组

python - Mayavi - 在线框中隐藏 "diagonal"行

用于匹配指定文本的正则表达式,然后是除指定文本之外的任何内容,然后是任何内容,然后是指定文本

regex - 这个查找/替换可以用一个正则表达式完成吗?

bash - 按列消除部分重复行并保留最后一行

python - 从文件中删除行

python - 在树递归期间保存路径