Reading .txt with multiple delimiters
35 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(2 个)
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|';
0 个评论
Jeremy Hughes
2021-8-14
Readtable accepts multiple delimiters. Try this:
T = readtable(filename,"Delimiter",[" ","|"])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!