2016-08-17 103 views
0

我有这个代码来搜索文本文件中的5个最常见的单词,但我不能在程序结束时使用排序和反向功能...我将如何避免使用他们?在文本文件python中的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)) 
+0

我认为当你使用排序,你应该扭转之前保存结果,所以'counts.sort()'不更新计数 – d3r1ck

+0

计数(或排序)之前,你可能要“正常化'的话。小写?德变复数?删除动词结尾? –

回答

0

使用sorted()功能,并将结果保存在一个变量,然后扭转它是这样的:

counts = sorted(counts, reverse=True) 

这行代码列表进行排序和扭转它为您和保存计数结果。然后你可以根据需要使用你的计数。

4
from collections import Counter 

c = Counter(words) 
c.most_common(5) 
相关问题