编写程序,统计文件“Nixon.txt”中出现频率最高的20个单词,并将统计结果写入“Tongji.txt”文件中。(注意:除去'the','and','to','of','a','be','from','in','for'等无意义的单词。)
时间: 2023-12-13 18:04:47 浏览: 26
好的,这是一个比较典型的文本处理任务,需要用到Python语言和一些常用的文本处理库。以下是代码实现的步骤:
1. 读取文件,将文件内容存储到一个字符串中。
2. 对字符串进行预处理,去除标点符号,转换为小写,分割成单词列表。
3. 创建一个字典,用于存储单词出现的次数。
4. 遍历单词列表,统计每个单词出现的次数,更新到字典中。
5. 对字典按照值进行排序,取前20个出现频率最高的单词。
6. 将结果写入文件。
下面是实现代码:
```python
import re
from collections import Counter
# 读取文件内容
with open('Nixon.txt', 'r') as f:
content = f.read()
# 预处理文本,去除标点符号,转换为小写,分割成单词列表
words = re.findall(r'\b\w+\b', content.lower())
stopwords = ['the', 'and', 'to', 'of', 'a', 'be', 'from', 'in', 'for'] # 无意义单词列表
words = [w for w in words if w not in stopwords]
# 统计单词出现频率
word_count = Counter(words)
# 取出现频率最高的20个单词
top_words = word_count.most_common(20)
# 将结果写入文件
with open('Tongji.txt', 'w') as f:
for word, count in top_words:
f.write(f'{word}\t{count}\n')
```
这个程序会将出现频率最高的20个单词写入到文件“Tongji.txt”中。你可以根据自己的需要修改文件名、排除的无意义单词等参数。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)