How can I Read specific parts(formatted) of an unformatted text file?

4 次查看(过去 30 天)
Hi guys,
I got confused about reading specific parts of an unformatted text. My text is something like this :
First 50(this number can vary) rows are in different length and consist of stings and number..
Then a specific pattern comes, and let say it is:
0 Alpha Beta A B C D E F G H I K
I want the skip the next and read the next 20(this number can change too) rows and 12 columns that consist of numbers.
Then I want to skip the lines till I met
0 X Y Z K L M N P R
I want the skip the next and read the next 20(this number can change too) rows and 9 columns that consist of numbers.
(Columns are tab separated)
I got very confused. Can any one Help me ?
  2 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2016-8-10
编辑:Azzi Abdelmalek 2016-8-10
This is not clear. Post a sample representing your text file and explain what you want to read
Brasco , D.
Brasco , D. 2016-8-12
I added a sample. I want the Alpha and Number lines to get extracted from the text.

请先登录,再进行评论。

采纳的回答

dpb
dpb 2016-8-10
编辑:dpb 2016-8-12
Just read and ignore 'til you find the specific stuff looking for...*regexp* can do this or you can just read and test...
fid=fopen('yourfile.txt','r');
j=0; % counter for data cells found
while ~feof(fid) % go to end
l=fgetl(fid); % read a line
if isempty(strfind(l(2:end),'ALPHA')),continue,end % skip if not what want
j=j+1; % increment the counter
title(j)=cellstr(l(3:end)); % title line w/o leading '0'
data{j}=textscan(fid,repmat('%f',1,9),'collectoutput',1,'headerlines',1); % read data
end
fid=fclose(fid);
% do whatever with data in the resulting cell array
...
  2 个评论
Brasco , D.
Brasco , D. 2016-8-12
编辑:Brasco , D. 2016-8-12
Thank you for your reply. Your code doesn't work exactly but I got the idea about catching the pattern line in the text. I think I could manage further. Thank you again.
By the way. I added a sample.
dpb
dpb 2016-8-12
Based on your later comment above and the sample file, all you need to search for is 'ALPHA', save that line as cellstr in cell array and then read the data block. NB: that portion of the file appears to have been written with Fortran (the '0' carriage control would seem to be the giveaway in the first column). That's not of any particular problem/concern other than you'll probably want to skip it in the actual end result and you'll need a 'headerlines',1 in the textscan call to space over that record before reading the data. It appears from the file you attached you could use a counted number of records if desired; this appears to be uniform but that may/may not be true in general?
I modified Answer just a little on this basis...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by