Question about taking data from a .txt file
조회 수: 2 (최근 30일)
이전 댓글 표시
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
Azzi Abdelmalek
2015년 6월 19일
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?
채택된 답변
Azzi Abdelmalek
2015년 6월 19일
fid = fopen('fic.txt');
line1 = fgetl(fid);
k=0;
while ischar(line1)
k=k+1;
res{k,1}=line1;
line1 = fgetl(fid);
end
fclose(fid);
idx1=find(~cellfun(@isempty,regexpi(res,'room')))
idx2=[idx1(2:end)-1; numel(res)]
for k=1:numel(idx1)
out{1,k}=res{idx1(k)}
out{2,k}=res(idx1(k)+1:idx2(k))
end
추가 답변 (1개)
Stephen23
2015년 6월 19일
편집: Stephen23
2015년 6월 19일
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:
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!