如何使用matlab搜索文本文件中的Count特定单词?

时间:2017-01-03 12:16:36

标签: matlab text-processing text-parsing textscan

我需要在matlab中编写一个程序,在文本文件中搜索特定的关键词,然后在文本中计算这个特定单词的编号。

2 个答案:

答案 0 :(得分:1)

首先看看如何使用Matlab读取文本文件,然后使用textscan函数将整个数据读入单元格数组,该函数是Matlab中的内置函数,并将数组的每个元素与特定关键字进行比较使用strcmp

我提供了一个函数,它将文件名和关键字作为输入,并输出文件中存在的关键字数。

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

答案 1 :(得分:0)

Matlab实际上有一个函数strfind可以为你做这个。查看Mathworks doc了解详情。

文本文件的内容应存储在变量中:

text = fileread('filename.txt')