Is it possible to use two textscan statements in a row ?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Gwendal Marrec
il 28 Mar 2022
Commentato: Gwendal Marrec
il 30 Mar 2022
Hello,
I am trying to extract some data from a text file.
My text file contains several lines written this way:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/943949/image.png)
I want to extract the parameters after the colons.
Here's my code :
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/943954/image.png)
It is supposed to return me C1 = "Mars 2022" and C2 = "16:17:50".
I get the following error message :
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/943959/image.png)
It seems like I cannot use two textscan statements in a row. In the workspace, C1 = "Mars 2022" but C2 is an empty cell.
Two additional questions :
- how to handle the empty string after 'nom' ? I would like that C3 = "".
- 'affaire' has multiple occurences within my textfile, but I'm only interested in the first one. How to do so ?
Any help would be greatly appreciated,
Gwendal
Risposta accettata
Stephen23
il 28 Mar 2022
Modificato: Stephen23
il 28 Mar 2022
"Is it possible to use two textscan statements in a row ?"
Yes, you can call TEXTSCAN as many times as you want on one file, I have often used this to read blocks of data separated by intermediate "header" lines. Quite handy, but probably not the best approach for your data file.
str = fileread('textscan_error.txt');
tmp = regexpi(str,'(?<=INFORMATION\s*\{\s*)[^\}]+','once','match');
tkn = regexp(tmp,'(\w+)\s*:\s*"([^"]*)','tokens');
tkn = vertcat(tkn{:}).';
out = struct(tkn{:})
out.heure
out.affaire
If you really want to use TEXTSCAN:
opt = {};
fmt = '%s:%q';
[fid,msg] = fopen('textscan_error.txt','rt');
assert(fid>0,msg)
str = 'X';
while ~startsWith(str,'INFORMATION')
str = fgetl(fid);
end
tmp = textscan(fid,fmt,opt{:});
fclose(fid);
tmp{:}
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Text Data Preparation in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!