Reading .txt with multiple delimiters

57 ビュー (過去 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';
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 日
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",[" ","|"])

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by