How do i change my script to print out the second word of each even line?

조회 수: 1 (최근 30일)
fn = input( 'file name: ', 's' );
fh = fopen( fn, 'r' );
ln = '';
count=1;
while ischar( ln )
ln = fgets( fh );
if (ischar( ln ) && mod(count,2)==0)
fprintf( ln );
end
count=count+1;
end
fclose( fh );
I created a script that prints out the even line of a input file but i dont know how to make it print out the second word of each even line.

채택된 답변

Adam Danz
Adam Danz 2019년 11월 7일
편집: Adam Danz 2019년 11월 7일
Instead of reading the file line by line you could read in the entire text file and then extract the 2nd word from even numbered lines of the text with just 3 lines of code.
% Read entire file as a char array
C = fileread('MyTextFile.txt');
% Split the char array by line and then split by word.
% ca{j}{m} is the m_th word in the j_th line of text.
ca = cellfun(@strsplit,strtrim(strsplit(C, newline())),'UniformOutput',false);
% get 2nd word of each even numbered line unless the line only has 1 word.
% If the line is empty, it will return an empty.
words = cellfun(@(s)s{min(numel(s),2)},ca(2:2:end),'UniformOutput',false);
% [1]^ [2]^^^^^^^^
% [1] get 2nd word
% [2] isolate even-numbered lines
If you'd rather maintain your fgets method, add the two lines below to display the 2nd word of ln unless it only has 1 word in which case it displays the first word.
lnSplit = strsplit(ln);
fprintf('%s\n',lnSplit{min(numel(lnSplit),2)})
% ^^ Assuming you want a line break
  댓글 수: 6

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by