首页 > 解决方案 > 如何读取文本文件并在其中找到特定值?

问题描述

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

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 
n:3 mse_avg:10.89 mse_y:16.33 mse_u:0.00 mse_v:0.00 psnr_avg:37.76 psnr_y:36.00 psnr_u:inf psnr_v:inf 
n:4 mse_avg:12.45 mse_y:18.67 mse_u:0.00 mse_v:0.00 psnr_avg:37.18 psnr_y:35.42 psnr_u:inf psnr_v:inf 

我需要在单独的行中读取每一行并使用readvarsmatlab函数,但输出仅n如下

n
n
n
n

它不能提取其他变量。你知道是什么问题吗?Matlab 还有其他读取文本文件的功能吗?

标签: matlab

解决方案


您最初的问题询问仅提取npsnr_avg. 我不确定这是意外还是有意编辑的。

如果情况仍然如此,请尝试对这些行进行文本扫描,然后提取npsnr_avg使用命名的正则表达式标记

fid = fopen('data.txt');
data = textscan(fid, '%s', 'delimiter', '\n');
fclose(fid);

M = regexp(data{1}, 'n:(?<n>\d+).*psnr_avg:(?<psnr_avg>[^\s]+)', 'names');
>> M{:}

ans = 

  struct with fields:

           n: '1'
    psnr_avg: '38.86'


ans = 

  struct with fields:

           n: '2'
    psnr_avg: '37.27'


ans = 

  struct with fields:

           n: '3'
    psnr_avg: '37.76'


ans = 

  struct with fields:

           n: '4'
    psnr_avg: '37.18'

推荐阅读