簡體   English   中英

讀取 python 中的文本文件並在每一行中提取特定值?

[英]read text file in python and extract specific value in each line?

我有一個文本文件,它的每一行如下:

 n:1 mse_avg:8.46 mse_y:12.69 mse_u:0.00 mse_v:0.00 psnr_avg:38.86 psnr_y:37.10 psnr_u:inf psnr_v:inf 
 n:2 mse_avg:12.20 mse_y:18.30 mse_u:0.00 mse_v:0.00 psnr_avg:37.27 psnr_y:35.51 psnr_u:inf psnr_v:inf 
    

我需要讀取每一行提取 psnr_y 及其在矩陣中的值。 python 還有其他讀取文本文件的功能嗎? 我需要從每一行中提取 psnr_y 。 我有一個 matlab 代碼,但我需要一個 python 代碼,我不熟悉 python 中的功能。 你能幫我解決這個問題嗎? 這是 matlab 代碼:

opt = {'Delimiter',{':',' '}};
fid = fopen('data.txt','rt');
nmc = nnz(fgetl(fid)==':');
frewind(fid);
fmt = repmat('%s%f',1,nmc);
tmp = textscan(fid,fmt,opt{:});
fclose(fid);
fnm = [tmp{:,1:2:end}];
out = cell2struct(tmp(:,2:2:end),fnm(1,:),2)

使用正則表達式

r'psnr_y:([\d.]+)'

在每一行讀取

並從結果中提取match.group(1)

如果需要轉換為浮點數: float(match.group(1))

由於我討厭正則表達式,我建議:

s = 'n:1 mse_avg:8.46 mse_y:12.69 mse_u:0.00 mse_v:0.00 psnr_avg:38.86 psnr_y:37.10 psnr_u:inf psnr_v:inf \nn:2 mse_avg:12.20 mse_y:18.30 mse_u:0.00 mse_v:0.00 psnr_avg:37.27 psnr_y:35.51 psnr_u:inf psnr_v:inf' 
lst = s.split('\n')
out = []
for line in lst:
  psnr_y_pos = line.index('psnr_y:')
  next_key = line[psnr_y_pos:].index(' ')
  psnr_y = line[psnr_y_pos+7:psnr_y_pos+next_key]
  out.append(psnr_y)
print(out)

out是每行中psnr_y值的列表。

您可以使用如下正則表達式:

import re

with open('textfile.txt') as f:
    a = f.readlines()
    pattern = r'psnr_y:([\d.]+)'
    for line in a:
        print(re.search(pattern, line)[1])

此代碼將僅返回 psnr_y 的值。 您可以刪除 [1] 並用 [0] 更改它以獲得完整的字符串,如“psnr_y:37.10”。 如果要將其分配到列表中,代碼如下所示:

import re

a_list = []

with open('textfile.txt') as f:
    a = f.readlines()
    pattern = r'psnr_y:([\d.]+)'
    for line in a:
        a_list.append(re.search(pattern, line)[1])

對於無需導入其他模塊的簡單答案,您可以嘗試:

rows = []
with open("my_file", "r") as f:
    for row in f.readlines():
        value_pairs = row.strip().split(" ")
        print(value_pairs)
        values = {pair.split(":")[0]: pair.split(":")[1] for pair in value_pairs}
        print(values["psnr_y"])
        rows.append(values)

print(rows)

這為您提供了一個字典列表(基本上是 JSON 結構,但帶有 python 對象)。 這可能不是最快的解決方案,但結構很好,您不必使用正則表達式

import fileinput
import re

for line in fileinput.input():
    row = dict([s.split(':') for s in re.findall('[\S]+:[\S]+', line)])
    print(row['psnr_y'])

驗證,

python script_name.py < /path/to/your/dataset.txt

暫無
暫無

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

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