简体   繁体   中英

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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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