How to read a text file and only keep certain numbers?

3 vues (au cours des 30 derniers jours)
cherrymath78
cherrymath78 le 2 Mai 2016
Modifié(e) : Robert le 4 Mai 2016
Hi,
I have a text file which contains the information listed below: (similar format)
-------------------------------
Info1.txt
Number: 01
Graduation Year: 2005
Class: 1268
Age: 32
Info2.txt
Number: 02
Graduation Year: 2006
Class: 8640
Age: 31
Info3.txt
Number: 03
Graduation Year: 2005
Class: 5309
Age: 32
Info4.txt
Number: 04
Graduation Year: 2005
Class: 2954
Age: 32
----------------------------
I’m trying to write a Matlab code that reads this .txt file and gives me only the class numbers as a list:
1268
8640
5309
2954
Thanks a lot!
  1 commentaire
Stephen23
Stephen23 le 2 Mai 2016
Modifié(e) : Stephen23 le 2 Mai 2016
@cherrymath78: please edit your question and upload a copy of the file using the paperclip button.
You should change the names if they should not be released publicly.

Connectez-vous pour commenter.

Réponses (1)

Robert
Robert le 2 Mai 2016
Modifié(e) : Robert le 4 Mai 2016
Once you have the data in MATLAB ( fileread will do the trick) you can use regular expressions to find your data. Use MATLAB's regexp to search for consecutive digits that follow the string "Class: ".
str = fileread(fid); % Fixed based on comment below. Thanks, Walter!
classNums = regexp(str,'(?<=Class: )\d+','match')
classNums = str2double(classNums)
  1 commentaire
Walter Roberson
Walter Roberson le 2 Mai 2016
The fopen/fread/fclose can be replaced by
str = fileread('myFile.txt');

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by