Skip to main content
 首页 » 编程设计

python之文本文件 python 中最常见的 5 个单词

2025年05月04日25mate10pro

我有这段代码可以在文本文件中搜索 5 个最常用的词,但我不能在程序末尾使用排序和反向函数...我该如何避免使用它们?

words = open('romeo.txt').read().lower().split() 
 
 
uniques = [] 
for word in words: 
  if word not in uniques: 
    uniques.append(word) 
 
 
counts = [] 
for unique in uniques: 
  count = 0               
  for word in words:      
    if word == unique:    
      count += 1          
  counts.append((count, unique)) 
 
counts.sort()             
counts.reverse()          
 
for i in range(min(5, len(counts))): 
  count, word = counts[i] 
  print('%s %d' % (word, count)) 

请您参考如下方法:

from collections import Counter 
 
c = Counter(words) 
c.most_common(5)