【问题标题】:Matlab; how to extract information from a header's file (text file)MATLAB;如何从头文件(文本文件)中提取信息
【发布时间】:2015-08-20 22:36:37
【问题描述】:

我有许多文本文件,它们有 35 行标题,后跟一个带有图像数据的大矩阵(该信息可以忽略,目前不需要阅读)。我希望能够读取标题行并提取这些行中包含的信息。例如标题的前几行是..

File Version Number: 1.0 

    Date: 06/05/2015

    Time: 10:33:44 AM
    ===========================================================
    Beam Voltage (-kV) = 13.000

    Filament (W) = 4.052

    Cond.  (-kV) = 8.885

    CenterX1 (V) = 10.7

    CenterY1 (V) = -45.9

    Objective (%) = 71.40

    OctupoleX = -0.4653

    OctupoleY = -0.1914

    Angle (deg) = 0.00

.

我希望能够打开这个文本文件并读取文件创建的日期和时间、灯丝功率、电容器电压、角度等。并将这些保存在变量中或发送到GUI 程序上的文本框。

我已经尝试了几件事,但是由于我想提取的值有时是在“=”之后或在“:”之后,或者只是在“”之后,所以我不知道如何处理这个问题。也许阅读每一行并寻找一个单词的匹配项?

任何帮助将不胜感激。

谢谢, 亚历克斯

【问题讨论】:

    标签: matlab text-files


    【解决方案1】:

    这并不是特别困难,其中一种方法是按照您的建议逐行解析。像这样的:

    MAX_LINES_TO_READ = 35;
    
    fid = fopen('input.txt');
    lineCount = 0;    
    
    dateString = '';
    beamVoltage = 0;
    while ~eof(fid)
        line = fgetl(fid);
        lineCount = lineCount + 1;
    
        %//check conditions for skipping loop body
        if isempty(line)
            continue
        elseif lineCount > MAX_LINES_TO_READ
            break
        end
    
        %//find headers you are interested in
        if strfind(line, 'Date')
            %//find the first location of the header separator
            idx = find(line, ':', 1);
            %//extract substring starting from 1 char after separator
            %//note: the trim is to get rid of leading/trailing whitespace
            dateString = strtrim(line(idx + 1 : end));
        elseif strfind(line, 'Beam Voltage')
            idx = find(line, '=', 1);
            beamVoltage = str2double(line(idx + 1 : end));
        end
    end
    
    fclose(fid);
    

    【讨论】:

      猜你喜欢
      • 2011-09-14
      • 2022-12-04
      • 2014-05-27
      • 2015-05-24
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多