【问题标题】:read text file in python and extract specific value in each line?在python中读取文本文件并在每一行中提取特定值?
【发布时间】:2021-05-04 15:19:58
【问题描述】:

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

 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)

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你可以像下面这样使用正则表达式:

    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])
    

    【讨论】:

      【解决方案2】:

      使用正则表达式

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

      在每一行读取

      并从结果中提取match.group(1)

      如果需要转换为浮点数:float(match.group(1))

      【讨论】:

        【解决方案3】:

        由于我讨厌正则表达式,我建议:

        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 值的列表。

        【讨论】:

          【解决方案4】:

          对于不需要导入其他模块的简单答案,您可以尝试:

          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 对象)。 这可能不是最快的解决方案,但结构很好,您不必使用正则表达式

          【讨论】:

            【解决方案5】:
            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
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-12-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-07-16
              • 1970-01-01
              相关资源
              最近更新 更多