本答案参考多次询问ChatGPT-3.5后选择的最佳回答,若是满意,还请采纳,谢谢。
import string
def process_file():
word_count = {}
with open('hamlet.txt', 'r') as f:
for line in f:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
items = list(word_count.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
word, count = items[i]
print(f"{word:<10},{count:>5}")
if __name__ == '__main__':
process_file()
在上述代码中:
- 首先定义了
process_file函数,在函数内部,首先创建了一个空的字典word_count用于存储单词和其出现的频率。 - 然后打开
hamlet.txt文件,对于文件中的每一行,先去除标点符号(通过translate方法结合string.punctuation),再转换为小写字母,然后将每行分割成单词列表。 - 对于每个单词,如果不在
word_count字典中,则将其加入字典且计数为1,否则将其计数加1。 - 之后将字典转换为包含元组(单词,计数)的列表
items,并按照计数从大到小排序。 - 最后取前10个元素,按照要求的格式打印输出。