python - python 正则表达式读取部分文本文件
问题描述
我有一个.txt
看起来像的文件
'type': 'validation', 'epoch': 91, 'loss': tensor(294.8862, device='cuda:0'), 'acc': tensor(1.00000e-02 *
9.9481), 'kl': tensor(292.5818, device='cuda:0'), 'likelihood': tensor(-2.3026, device='cuda:0')}{'type': 'train', 'epoch': 92, 'loss': tensor(51.1491, device='cuda:0'), 'acc': tensor(1.00000e-02 *
9.9642), 'kl': tensor(48.8444, device='cuda:0'), 'likelihood': tensor(-2.3026, device='cuda:0')}
我想读出它acc
来绘制它。我的代码有什么问题?
acc = list(map(lambda x: x.split(" ")[-1], re.findall(r"(acc: \d.\d+)", file)))
print(re.findall(r"(acc: \d.\d+)", file))
train = acc[0::3]
valid = acc[1::3]
return np.array(train).astype(np.float32), np.array(valid).astype(np.float32)
谢谢你的帮助!
解决方案
如果您需要acc
尝试的值。
import re
acc = []
with open(filename, "r") as infile:
acc = re.findall(r"'acc':\s+tensor\((.*?)\)", infile.read())
print(acc)
输出:
['1.00000e-02 *9.9481', '1.00000e-02 *9.9642']
或者,如果您只需要使用浮点值。
acc = [float(i.split("*")[-1].strip()) for i in acc]
print(acc) # -->[9.9481, 9.9642]
推荐阅读
- yarnpkg - 如何让 `npx mrm lint-staged` 工作
- java - 如何为将记录保存在数据库中的 void 方法编写 JUnit 5 测试?
- ruby-on-rails - 从 Rails 5.2 迁移到 Rails 6.0 后,ActiveRecord::ConnectionNotEstablished 随机出现在部署实例中
- node.js - 使用 mongodb 获取特定半径内所有用户的最佳方法是经纬度?
- oracle - 选择oracle union and union all 没有显示部门名name
- python - Python中的宽度和高度中心对齐PIL
- asp.net - ASP.Net WebAPI 无法连接到 Dockerized Cloud Sql 代理
- integration-testing - 如何在集成测试中使测试替身保持最新
- reactjs - Next js : 如何更改 PostCSS 模块 CSS 前缀 + 后缀格式?
- python-3.x - 将节点列表转换为python中的嵌套字典