Search code examples
matlabtext-processingtext-parsingtextscan

How can I search a text file for Count specific words using matlab?


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.


Solution

  • 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