使用python,假设当前文件夹下有一个英文的文本文件hamlet.txt,编写程序,统计该英文中单词的出现次数,并将出现次数最多的前20个单词及出现次数按降序显示在屏幕的同时也存到python3.csv文件中。
时间: 2023-05-23 08:00:51 浏览: 93
好的,以下是代码:
```
import string
# 读取文件
with open('hamlet.txt', 'r') as f:
data = f.read()
# 处理数据
data = data.lower() # 转为小写
for c in string.punctuation: # 去除标点符号
data = data.replace(c, ' ')
words = data.split() # 分割为单词列表
# 统计单词出现次数
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 输出前20个单词及出现次数
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:20]
print('Top 20 words:')
for word, count in top_words:
print(f'{word}: {count}')
# 存储到csv文件中
with open('python3.csv', 'w') as f:
f.write('Word,Count\n')
for word, count in top_words:
f.write(f'{word},{count}\n')
```
希望这能够解决您的问题!
阅读全文