How can I search a text file for specific words using MATLAB?
I need to write a program in matlab that searches for key words in a text file and then reads in what comes after those words, then continue searching. The text file will have headings that trigger the program to store the strings after them. I looked at the fscanf method in the matlab help files on their web page, but I am not sure how to make this search word by word rather than character by character. Any help would be appreciated!
Public Comments
- Ctrl-F>MATLAB
- This will read in a text file and do as you request. Y!A screws up coding by adding for instance "..." so let me know if you have difficulties. I tested with a text file and it was fine, it may fail if your text file starts with spaces. It doesn't distinguish words suffixed by a comma without a space from words. Best of luck... clc; clear all; searchterm='word' ; fid=fopen('notes.txt'); f=fscanf(fid,'%c'); [m n]=size(f); inc=0; wrdinc=1; for chr=1:n inc=inc+1; if f(inc)==' '; wordc{wrdinc}=f(1:inc-1); f(1:inc)=[]; wrdinc=wrdinc+1; inc=0; end end [m n]=size(wordc); for i=1:n m=char(wordc{i}); if strcmp(wordc{i},searchterm)==1; disp(['Word discovered appears as word number: ',num2str(i),' of ',num2str(n),' words !']) disp(['Search term: ',wordc{i}]) if (i>1) disp(['Word before search term: ',wordc{i-1}]) disp(['Word after search term: ',wordc{i+1}]) else if i==1 disp(['Can not display the word before the searched term if the searched word is the first word']) disp(['Word after search term: ',wordc{i+1}]) end if i==n disp(['Can not display the word after the searched term if the searched word is the last word']) disp(['Word before search term: ',wordc{i-1}]) end end disp(['oOoOoOo']) end end
Powered by Yahoo! Answers