How to delete the words/characters from a .txt file?
36 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2022-4-1
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 个评论
更多回答(2 个)
per isakson
2022-4-1
编辑:per isakson
2022-4-2
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 个评论
DGM
2022-4-1
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 个评论
另请参阅
类别
在 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!