Reading .txt with multiple delimiters

조회 수: 29(최근 30일)
Another Mouse
Another Mouse 2021년 8월 11일
답변: Jeremy Hughes 2021년 8월 14일
I want to read a .txt file with multiple delimiters. One line of the file looks like this:
Sensor 1| 00150| 2283 mSec| 0.221 3.183 11.055| 0.0353 0.0023 -0.6950 0.7182|
I had originally hardcoded to read the file like this, but occasionally it will incorrectly read NaN (probably due to unseen differences in spacing on some lines of the data file) when there is clearly a value present. This works for some files but not all.
fileID = fopen('R1.txt','r');
formatSpec = '%40c %8f %9f %6f %1c %11f %10f %8f %8f';
I then tried using a community board suggestion ( ) to read it using the following code, but could not figure out how to separate the groups of numbers within colunms 4 and 5 of fieldarray:
%read file
filestr = fileread('R1.txt');
%break it into lines
filebyline = regexp(filestr, '\n', 'split');
%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{:});
Is there a better way to approach this?


Wan Ji
Wan Ji 2021년 8월 14일
If each line in the file is of the same format, I recommend the following formatSpec
formatSpec = 'Sensor %d| %d| %f mSec| %f %f %f| %f %f %f %f|';

Jeremy Hughes
Jeremy Hughes 2021년 8월 14일
Readtable accepts multiple delimiters. Try this:
T = readtable(filename,"Delimiter",[" ","|"])




Community Treasure Hunt

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

Start Hunting!

Translated by