[Python]列出一部英文小说中,出现频率前10的单词

# 找出一篇小说中出现最频繁的排名前10的单词
file = open("novel.txt")
# 创建一个字典用于存储每个单词出现的次数
word_appear_time = {}
for line in file:
    words = line.strip().split()
    for word in words:
        if word in word_appear_time:
            word_appear_time[word] += 1
        else:
            word_appear_time[word] = 1

word_list = []
for word, times in word_appear_time.items():
    word_list.append((times, word))

word_list.sort(reverse = True)
for times, word in word_list[:10]:
    print(word)
# 关闭文件句柄
file.close()

你可能感兴趣的:(Python)