How to delete the words/characters from a .txt file?
46 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Thomas McCutcheon
am 1 Apr. 2022
Bearbeitet: per isakson
am 2 Apr. 2022
I have data from a load cell that was written with uncessary characters in a .txt file (Attached). I only need the numbers from the data. Is there anyway to filter the words out? It would be even better if I could then convert that into a .csv file.
For example:
First line says
" Load_Cell_1==51.127 N -82.489 N -73.474 N -0.6313 Nm -0.2440 Nm -1.2160 Nm "
I want it to read
"51.127, -82.489, -73.474, -0.6313, -0.2440, -1.2160"
0 Kommentare
Akzeptierte Antwort
Voss
am 1 Apr. 2022
Here's one way to get just the numbers out, which you can then do whatever you want with, including writing to a csv file (using, e.g., writematrix):
% open, read, and close the file:
fid = fopen('loadcell_data.txt');
data = fread(fid,'*char').';
fclose(fid);
% split the text on '==' and 'Nm':
data = split(data,{'==' 'Nm'});
% remove empty element after final 'Nm':
if isempty(data{end})
data(end) = [];
end
% reshape to four columns:
data = reshape(data,4,[]).';
% now the second column of 'data' contains the first four
% columns of numbers in the file, and that still needs
% to be split on 'N' (couldn't do it before because 'Nm'
% also contains 'N').
% split the second column on 'N', combine with columns
% 3 and 4, and convert everything to double:
data = str2double([split(data(:,2),'N') data(:,[3 4])])
0 Kommentare
Weitere Antworten (2)
per isakson
am 1 Apr. 2022
Bearbeitet: per isakson
am 2 Apr. 2022
fid = fopen( 'loadcell_data.txt' );
cac = textscan( fid, '%*[^=]==%f%*s%f%*s%f%*s%f%*s%f%*s%f%*s' );
fclose( fid );
num = cell2mat( cac );
num(1:3,:)
And
writematrix( num, 'loadcell.csv' ) % or csvwrite()
0 Kommentare
DGM
am 1 Apr. 2022
There are probably faster or more robust ways, but here's one way.
alltext0 = fileread('loadcell_data.txt');
alltext0 = split(alltext0,newline);
numbers = regexp(alltext0,'[\s=]([-\d\.]*) Nm?','tokens');
numbers = vertcat(numbers{:});
numbers = cellfun(@str2double,numbers);
csvwrite('loadcell_data_modified.csv',numbers)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Text Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!