首页 > 解决方案 > 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)

谢谢你的帮助!

标签: pythonregex

解决方案


如果您需要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]

推荐阅读