MATLAB在某一行之后从文件中读取格式化的数字

时间:2018-02-08 02:37:50

标签: matlab text readfile

我有一个包含任意字符/数字行的文件。我需要在一行之后提取格式化的数字,如下所示:

Start of text file
Here is arbitrary lines of characters and numbers
  1 -100
  2 -200
...
ABC
1 2 3 
... 

Start extracting  the following formatted numbers after the blank line

                         10           1.5-04
                         20          -1.6-04
                        100           1.7-04
                        200           1.8-04
                        300          -1.9-04
                        400          -2.0-04

Stop reading when you find the previous blank line 
Then more arbitrary lines of characters and numbers 
    ABC
    1 2 3 
Then end of file 

使用MATLAB,问题是如何在到达“开始在空白后开始提取以下格式化数字”的行之后从(10 1.5-04)到(400 -2.0-04)之间提取两列格式化数字线。”请注意,此列的长度事先未知。

2 个答案:

答案 0 :(得分:0)

我使用regex从文本中提取数字,但我无法编写特定的表达式来提取两列,因为在这些值可以依赖之前和之后都没有这样的文本。

clear 
text = fileread('test_file.txt');
pattern = '(?=(\s|-)[\d]+)(-|\s)[\d]+';
%pattern = '((\s|-)[\d]+)';
out = regexp(text, pattern,'match')

我希望我的代码能给你一个想法^ - ^

答案 1 :(得分:0)

(1)逐行读取文件 (2)找到关键词后开始阅读 (3)读取格式化的数字 (4)完成格式化数字后保留文件

clc;close all; clear *
filename='Test.txt';
File = fopen(filename,'r');   
LineCont=0;                     %Line counter
Flag=0;                         %Flag to start extracting formatted numbers
st2='Start extracting the';     %Keyword

%Read file line by line
tline = fgetl(SGDFile);         %Read first line
while ischar(tline)
    Lcont=Lcont+1;              %Line number
    k = strfind(tline,st2);     %Check for keywork to start extracting 
    if ~isempty(k)              %Start extracting numbers
        Flag=1;                 %Flag to start reading formatted numbers
        Num=[];                 %Collect formatted numbers here
    end

    tline = fgetl(File);        %Move to next line
    if tline ~=-1               %If not empty
        if Flag==1
            value = strsplit(tline);            %Split numbers and text
            num= str2num(char(value))';         %Convert text to number
            if size(num,1)<1                    %Stop reading when blank
            break                               %Exit loop
            else                                
            Num=[Num;num];                      %Collect formatted numbers
            end  
        end
    end
end
fclose(File);

这可能是一种低效的方式,但它确实有效。