how to read a text file with delimiter ?

조회 수: 171 (최근 30일)
Amr Hashem
Amr Hashem 2015년 7월 25일
댓글: Amr Hashem 2015년 7월 25일
I have a large text file(.txt) with delimited data , delimiter (|)
which contain numbers, texts, empty cells
i want to open it in matlab , to be something like this
each delimited in a cell
how i can do this?
  댓글 수: 1
Amr Hashem
Amr Hashem 2015년 7월 25일
I try this:
fid = fopen( 'delimite.txt');
data = textscan(fid, '%f%f%s%s%s%s', 'Delimiter', '|','TreatAsEmpty','~');
fclose(fid);
but it gives me this :
which is not 100% correct

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2015년 7월 25일
%read file
filestr = fileread('YourFile.txt');
%break it into lines
filebyline = regexp(filestr, '\n', 'split');
%remove empty lines
filebyline( cellfun(@isempty,filebyline) ) = [];
%split by fields
filebyfield = regexp(filebyline, '\|', 'split');
%pad out so each line has the same number of fields
numfields = cellfun(@length, filebyfield);
maxfields = max(numfields);
fieldpattern = repmat({[]}, 1, maxfields);
firstN = @(S,N) S(1:N);
filebyfield = cellfun(@(S) firstN([S,fieldpattern], maxfields), filebyfield, 'Uniform', 0);
%switch from cell vector of cell vectors into a 2D cell
fieldarray = vertcat(filebyfield{:});
Now to be consistent with your diagram, we have to convert to numeric not column by column but rather item by item: your row #8 column #3 is converted to a number even though it is the only one in the column that is converted. This is unusual and would typically lead to problems further down the road, but it is what you said you wanted.
%convert all fields to numeric
numarray = str2double(fieldarray);
%switch to cell array of numbers
outarray = num2cell(numarray);
%the places that the strings could not be converted to numbers show up as NaN
conv_failed = isnan(numarray);
%replace the failed conversions with the original text in the cells
outarray(conv_failed) = fieldarray(conv_failed);
The first part of this code, leading up to the creation of "fieldarray", can be made much much compact if the maximum number of fields per line is known in advance.
fields_per_line = 73; %for example
fmt = repmat('%s',1,fields_per_line);
fid = fopen('YourTextFile', 'rt');
filebycolumn = textscan(fid, fmt, 'Delimiter', '|');
fclose(fid);
fieldarray = horzcat(filebycolumn{:});
  댓글 수: 1
Amr Hashem
Amr Hashem 2015년 7월 25일
Thanks
it works...
that is what i want :
fields_per_line = 6; %for example
fmt = repmat('%s',1,fields_per_line);
fid = fopen('delimite.txt', 'rt');
filebycolumn = textscan(fid, fmt, 'Delimiter', '|');
fclose(fid);
fieldarray = horzcat(filebycolumn{:});

댓글을 달려면 로그인하십시오.

추가 답변 (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