簡體   English   中英

python正則表達式讀取文本文件的部分

[英]python regex reading parts of text file

我有一個.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]

您的正則表達式是錯誤的...

在該文件中它的'acc'當你尋找acc:還之間'acc':和數值是tensor( ... )

試試:( ('acc': tensor\\(.+?\\))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM