I need to write a program in matlab that searches for specific key words in a text file and then Count the number of this specific word in text.
Asked
Active
Viewed 491 times
-4
-
4I'm voting to close this question as off-topic because it shows no effort and is probably just a do-my-homework type of question. Please edit to show what you've tried and what *specifically* isn't working. – gnovice Jan 03 '17 at 22:15
2 Answers
1
First look at how to read a text file using Matlab, then read the entire data into a cell array using textscan
function which is an in-built function in Matlab and compare each element of the array with specific keyword using strcmp
.
I have provided a function that takes filename and keyword as input and outputs the count of keywords present in the file.
function count = count_word(filename, word)
count = 0; %count of number of specific words
fid = fopen(filename); %open the file
c = textscan(fid, '%s'); %reads data from the file into cell array c{1}
for i = 1:length(c{1})
each_word = char(c{1}(i)); %each word in the cell array
each_word = strrep(each_word, '.', ''); %remove "." if it exixts in the word
each_word = strrep(each_word, ',', ''); %remove "," if it exixts in the word
if (strcmp(each_word,word)) %after removing comma and period (if present) from each word check if the word matches your specified word
count = count + 1; %increase the word count
end
end
end

Telepresence
- 619
- 2
- 7
- 22
0
Matlab actually has a function strfind
which can do this for you. Check the Mathworks doc for more details.
The content of the text file should be stored in a variable:
text = fileread('filename.txt')

rinkert
- 6,593
- 2
- 12
- 31