首页 > 解决方案 > 逐行读取文本文件并在 Python 中存储匹配特定模式的变量

问题描述

我们有一个包含以下两行的大型日志文件:

00 LOG     |   Cycles Run:  120001
00 LOG     ! Virtual: Max> ?????????? bytes (?.???? gb), Current> 640733184 bytes (?.???? gb).

00 LOG     ! Virtual: Max> 1082470400 bytes (?.???? gb), Current> ????????? bytes (?.???? gb).

00 LOG     ! Actual: Max> ????????? bytes (?.???? gb), Current> 472154112 bytes (?.???? gb).

00 LOG     ! Actual: Max> 861736960 bytes (?.???? gb), Current> ????????? bytes (?.???? gb).

由于日志文件很大,我们希望逐行读取(而不是一次读取缓冲区中的整个文本),匹配特定的模式集并在单独的变量中选择值。

例如

00 LOG     |   Cycles Run:  120001

我们希望 o 选择120001并存储在变量 saycycle中。

另一方面,我们解析这些行:

00 LOG     ! Virtual: Max> ?????????? bytes (?.???? gb), Current> 640733184 bytes (?.???? gb).

00 LOG     ! Virtual: Max> 1082470400 bytes (?.???? gb), Current> ????????? bytes (?.???? gb).

00 LOG     ! Actual: Max> ????????? bytes (?.???? gb), Current> 472154112 bytes (?.???? gb).

00 LOG     ! Actual: Max> 861736960 bytes (?.???? gb), Current> ????????? bytes (?.???? gb).

标有 的字符?可以是任何数字。

我们想存储如下变量:

640733184在变量中virtual_cur

1082470400在变量中virtual_max

472154112在变量中actual_cur

861736960在变量中actual_max

写了一个片段,Python 3.6但它正在打印空列表:

import re

filename = "test.txt"
with open(filename) as fp:  
   line = fp.readline()
   while line:
       cycle_num = re.findall(r'00 LOG     |   Cycles Run:  (.*?)',line,re.DOTALL)
       line = fp.readline()

print (cycle_num[0])

注意:我想在单独的变量中选择每个值并稍后使用它。需要一个一个地设置5个模式,如果它匹配任何特定的模式,则选择值并将其放置在各个变量中。

不确定第二个模式的通配符匹配。

请建议我们一种有效地做到这一点的方法。

标签: pythonregexpython-3.6readlinefindall

解决方案


使用正则表达式

(?:(?:Cycles Run:[ \t]+)|(?:Current>[ \t]+))(\d+)

演示

您可以按照以下方式做一些事情:

import re
pat=re.compile(r'(?:(?:Cycles Run:[ \t]+)|(?:Current>[ \t]+))(\d+)')
with open('test.txt','r') as f:   
    for line_num, line in enumerate(f):
        m=pat.search(line)
        if m:
            print(line_num, m.group(0))

推荐阅读