How to delete the words/characters from a .txt file?
33 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Thomas McCutcheon
el 1 de Abr. de 2022
Editada: per isakson
el 2 de Abr. de 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 comentarios
Respuesta aceptada
Voss
el 1 de Abr. de 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 comentarios
Más respuestas (2)
per isakson
el 1 de Abr. de 2022
Editada: per isakson
el 2 de Abr. de 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 comentarios
DGM
el 1 de Abr. de 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 comentarios
Ver también
Categorías
Más información sobre Text Files en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!