用matlab写上述代码
时间: 2023-12-30 17:02:29 浏览: 30
以下是用MATLAB实现的代码:
```matlab
clc;
clear;
% 读取文本文件内容
fileID = fopen('text.txt','r');
text = fscanf(fileID,'%c');
% 将文本转换为小写字母
text = lower(text);
% 去除标点符号
text = regexprep(text, '[^a-zA-Z0-9 ]', '');
% 分割文本为单词
words = strsplit(text);
% 统计每个单词出现次数
wordCount = containers.Map;
for i = 1:length(words)
if wordCount.isKey(words{i})
wordCount(words{i}) = wordCount(words{i}) + 1;
else
wordCount(words{i}) = 1;
end
end
% 按照出现次数从大到小排序
sortedWords = sort(words);
uniqueWords = unique(sortedWords);
wordFreq = zeros(length(uniqueWords), 1);
for i = 1:length(uniqueWords)
wordFreq(i) = wordCount(uniqueWords{i});
end
[sortedFreq, sortedIdx] = sort(wordFreq, 'descend');
sortedWords = uniqueWords(sortedIdx);
% 输出结果
for i = 1:length(sortedWords)
fprintf('%s: %d\n', sortedWords{i}, sortedFreq(i));
end
```
上述代码中,我们首先读取文本文件的内容,并将其转换为小写字母。然后,我们使用正则表达式去除标点符号,并将文本分割为单词。接着,我们使用Map数据结构统计每个单词出现的次数,并按照出现次数从大到小排序。最后,我们输出每个单词及其出现次数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)