Skip to main content
 首页 » 编程设计

来自 txt 文件的 Python 字数统计程序

2025年05月04日18shanyou

我正在尝试编写一个程序来计算 txt 文件中最常见的 5 个单词。

这是我目前所拥有的:

file = open('alice.txt') 
wordcount = {} 
 
for word in file.read().split(): 
    if word not in wordcount: 
        wordcount[word] = 1 
    else: 
        wordcount[word] += 1 
 
for k, v in wordcount.items(): 
    print (k, v) 

程序会计算 .txt 文件中的每个单词。

我的问题是如何让它只计算文件中最常见的 5 个单词,以便在每个单词旁边显示单词和单词计数。

有一个问题 - 我不会使用字典......无论那是什么意思。

请您参考如下方法:

很简单,您只需找到文件中最常见的 5 个词。

所以你可以这样做:

wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True) 

然后,这个字典将按值排序(记住 sorted 返回一个列表)。

您可以使用以下代码获取最常见的 5 个词:

for k, v in wordcount[:5]): 
    print (k, v) 

完整代码如下:

wordcount = {} 
 
with open('alice.txt') as file:  # with can auto close the file 
    for word in file.read().split(): 
        if word not in wordcount: 
            wordcount[word] = 1 
        else: 
            wordcount[word] += 1 
 
wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True) 
 
for k, v in wordcount[:5]: 
    print(k, v) 

此外,这里有一个更简单的方法来使用 collections.Counter :

from collections import Counter 
with open('alice.txt') as file:  # with can auto close the file 
    wordcount = Counter(file.read().split()) 
 
for k, v in wordcount.most_common(5): 
    print(k, v) 

输出与第一个解决方案相同。