Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python正则表达式读取部分文本文件_Python_Regex - Fatal编程技术网

python正则表达式读取部分文本文件

python正则表达式读取部分文本文件,python,regex,Python,Regex,我有一个.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': 9

我有一个
.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:
也在
'acc':
和数值之间是
张量(…)

尝试:
('acc':tensor\(.+?\)

您的文件看起来像JSON。我认为您应该使用json模块。@Rakesh:看起来根本不像json。错误的引号和错误的值。@MikeScotty。是的,你是对的…@Felix Laumann你能发布你的预期输出吗?也许可以更详细地指出,regex
acc:\d
acc:
之后查找空格和数字,并且在示例中没有出现这种模式。类似地,
\d\.\d+
只查找点两侧的数字序列,点之前只允许有一个数字;这显然不能匹配大于或等于10的数字、负数或指数/科学记数法中的数字。
acc = [float(i.split("*")[-1].strip()) for i in acc]
print(acc) # -->[9.9481, 9.9642]