如何知道一个段落中出现最多的词?(Matlab)

3

我有一个很长的段落,想知道其中出现最多的单词是什么。请问有哪些方法可以实现这个功能?带有示例和解释的回答将非常有帮助。谢谢!

2个回答

5
这是一种非常MATLAB化的方法。我尽量清晰地命名变量。请尝试每行代码并检查结果,以便理解其工作原理。核心函数: uniquehist
% First produce a cell array of words to be analyzed
paragraph_cleaned_up_whitespace = regexprep(paragraph, '\s', ' ');
paragraph_cleaned_up = regexprep(paragraph_cleaned_up_whitespace, '[^a-zA-Z0-9 ]', '');
words = regexpi(paragraph_cleaned_up, '\s+', 'split');

[unique_words, i, j] = unique(words);
frequency_count = hist(j, 1:max(j));
[~, sorted_locations] = sort(frequency_count);
sorted_locations = fliplr(sorted_locations);
words_sorted_by_frequency = unique_words(sorted_locations).';
frequency_of_those_words = frequency_count(sorted_locations).';

我还有点困惑你在这里做了什么...你能解释一下吗? - heinst
1
哦,我刚注意到这个答案,不错!我刚学会了unique的新功能! :) +1 - Barney Szabolcs

2
这里有一个简单的解决方案,应该非常快。
example_paragraph = 'This is an example corpus. Is is a verb?';

words = regexp(example_paragraph, ' ', 'split');
vocabulary = unique(words);
n = length(vocabulary);
counts = zeros(n, 1);
for i=1:n
    counts(i) = sum(strcmpi(words, vocabulary{i}));
end

[frequency_of_the_most_frequent_word, idx] = max(counts);
most_frequent_word = vocabulary{idx};

你还可以查看这里的答案,以获取数组中最常见的单词。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接