Reading text file word by word
Mostra commenti meno recenti
Input is the attached text file, with one long word, a newline, then several equal-length short words separated by white spaces. I would like to read the first word in a variable, then the other ones in another variable one by one, rather than all into a single string or into a single huge cell array. I tried to do this with fscanf in several ways, but failed, and even got the impression that fscanf is not complying with https://fr.mathworks.com/help/matlab/ref/fscanf.html no clue about what I am doing wrong.
fileID = fopen('dataset_300_8.txt');
long_word = fscanf(fileID, '%[$ACGT]'); % is there another way to stop reading at newline?
short_word = ' ';
while ~isempty(short_word)
short_word = fscanf(fileID, '%s'); % does not work: shouldn't %s stop as it encounters a white space?
% short_word = fscanf(fileID, '%10s'); % this also does not work
% short_word processing code here
end
fclose(fileID);
4 Commenti
madhan ravi
il 13 Ott 2018
Try my answer below
jonas
il 13 Ott 2018
I would just read the entire thing and split it, but I do not know if that satisfies the ' read one by one' requirement.
madhan ravi
il 13 Ott 2018
%10c and the delimiter does the work as my answer below.
Paolo Binetti
il 13 Ott 2018
Modificato: Paolo Binetti
il 13 Ott 2018
Risposta accettata
Più risposte (1)
Image Analyst
il 13 Ott 2018
"I would like to read the first word in a variable, then the other ones in another variable one by one, rather than all into a single string or into a single huge cell array." <--- this is a really bad idea. I'm sure Stephen will soon give you the reasons why.
Better solution is to use fileread() followed by strsplit() to make the single cell array.
str = fileread('dataset_300_8.txt'); % Read entire file.
ca = strsplit(str, ' '); % Put each word into a cell
1 Commento
Paolo Binetti
il 13 Ott 2018
Categorie
Scopri di più su Language Support in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!