一篇文章,出现了哪些词?哪些词出现的最多?
请统计hamlet.txt文件中出现的英文单词情况,统计并输出出现最多的5个单词,注意:
(1) 单词不区分大小写,即单词的大小写或组合形式一样;
(2) 请在文本中剔除英文标点符号;
(3) 输出5个单词,每个单词一行;
(4) 输出单词为小写形式。
注意:要读入的文件已放入当前目录下,源文件中直接读取此文件即可。
import re
from collections import Counter
# 读取文本文件
with open('hamlet.txt', 'r', encoding='utf-8') as file:
text = file.read()
# 剔除英文标点符号,将文本转换为小写
words = re.findall(r'\b\w+\b', text.lower())
# 统计单词出现次数
word_counts = Counter(words)
# 输出出现最多的5个单词
for word, count in word_counts.most_common(5):
print(word)