python - 逐行读取文本文件并在 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个模式,如果它匹配任何特定的模式,则选择值并将其放置在各个变量中。
不确定第二个模式的通配符匹配。
请建议我们一种有效地做到这一点的方法。
解决方案
使用正则表达式
(?:(?: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))
推荐阅读
- node.js - 使用 Sequelize with Node 和 Express 批量插入
- python - 如何将变量添加到json
- electron - 用于刷新的电子框架窗口管理不起作用
- open-source - Dia(图表软件)的开发是否永久停止?
- javascript - 如何使用 $http POST 传递对象参数并在 Nodejs 服务中访问
- scala - 使用 Gson.tojson 转换嵌套列表
- javascript - JavaScript 数组自动填充基于下拉选择?
- android - 如何从其他活动类调用自定义适配器类中存在的函数?
- python - 在 matplotlib 3D 中标记第一个和最后一个数据点
- javascript - Javascript 提示显示为未定义