Question about taking data from a .txt file
Mostrar comentarios más antiguos
I have a .txt that will have a group of that I need to pull out based off of a space being in between. For example, a certain chunk will have a title, followed by an unknown number of lines that start with a hyphen, that will then be followed by a space.
How can I pull out each block of hyphens into its own unique cell? I want it to start at the first hyphen of the group and end at the next space. I know I need to use a loop but I'm having trouble setting this up.
I've tried setting up a combination of for/while loops while using if statements but I'm having no luck.
Any sort of help will be appreciated.
4 comentarios
Azzi Abdelmalek
el 19 de Jun. de 2015
Can you post an example, and ask clearly what you want.
Choke
el 19 de Jun. de 2015
Azzi Abdelmalek
el 19 de Jun. de 2015
This is not clear, Room 1 is in cell{1,1} or in cell{2,1}? can you just post the expected result for this example?
Respuesta aceptada
Más respuestas (1)
There is no need to use any slow loops for this, when regexp does it all in one go:
fmt = '(^Room \d+)\s*\n(^- \d+ [^\n]+(\n|$))+';
str = fileread('temp.txt');
C = regexpi(str,fmt,'lineanchors','tokens');
C = vertcat(C{:});
and the output looks like this:
>> C
C =
'Room 1' [1x35 char]
'Room 2' [1x49 char]
'Room 3' [1x43 char]
>> C{1,2}
ans =
- 6 chairs
- 5 tables
- 2 lamps
And of course you can do something similar with the names in the second column, if you wish to split them into separate cells. I used my FEX submission to help generate the regexp regular expression:
And this is the file that I used:
1 comentario
Choke
el 19 de Jun. de 2015
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!