Reading .txt with multiple delimiters

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';
A=textscan(fileID,formatSpec);
I then tried using a community board suggestion ( https://www.mathworks.com/matlabcentral/answers/231118-how-to-read-a-text-file-with-delimiter ) 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?

답변 (2개)

Wan Ji
Wan Ji 2021년 8월 14일

0 개 추천

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일

0 개 추천

Readtable accepts multiple delimiters. Try this:
T = readtable(filename,"Delimiter",[" ","|"])

카테고리

도움말 센터File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

제품

릴리스

R2017b

질문:

2021년 8월 11일

답변:

2021년 8월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by