Writing a script to take a text file and display the second word in each even numbered row
3 ビュー (過去 30 日間)
古いコメントを表示
Would someone be able to help me with a rather simple script I have to write? The script needs to be able to take a text file and display the second word of every even numbered line. Any help is greatly appreciated!
0 件のコメント
回答 (1 件)
Bob Thompson
2019 年 4 月 2 日
One of the simplest ways to do this is by looping through each line with fgetl, and splitting the appropriate lines with regexp. Below is a sample of how to do this.
fid = fopen('mytextfile.txt'); % open the file
fgetl(fid); line = fgetl(fid); % capture the second line
c = 2; % Track line number for troubleshooting
word = []; % initialize blank results array
while ~isnumeric(line);
tmp = regexp(line,'','split'); % split the line by whitespace
word = [word; tmp{1}{2}]; % copy second word onto end of list
fgetl(fid); line = fgetl(fid); % advance to next second line
c = c + 2; % counting lines
end
I have not tested this sample, so there may be some hiccups with a bit of the logic or the indexing. Note that regexp is particularly strange with its indexing, so if tmp{1}{2} returns an error, double check that the indexing is correct before looking to other solutions.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!