简体   繁体   English

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

[英]5 most common words in text file python

i have this code to search for the 5 most common words in a text file but i cant use the sort and reverse functions at the end of the program... how would i avoid using them? 我有这段代码可以在文本文件中搜索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)

Use the sorted() function and save the results in a variable then reverse it like this: 使用sorted()函数并将结果保存在变量中,然后将其反转,如下所示:

counts = sorted(counts, reverse=True)

That line of code will sort the list and reverse it for you and save the results in counts. 该行代码将对列表进行排序并为您反向,并将结果保存为计数。 Then you can use your count as required. 然后,您可以根据需要使用计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM