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你能发布你的预期输出吗?也许可以更详细地指出,regexacc:\d
在acc:
之后查找空格和数字,并且在示例中没有出现这种模式。类似地,\d\.\d+
只查找点两侧的数字序列,点之前只允许有一个数字;这显然不能匹配大于或等于10的数字、负数或指数/科学记数法中的数字。
acc = [float(i.split("*")[-1].strip()) for i in acc]
print(acc) # -->[9.9481, 9.9642]