0

I have this program that reads a file and prints the desired amount of most common words. I don't know how to print the words that appear the same amount of times.

Here's my code:

words = open(input('Enter the name of the file: ')).read().lower().split()
number_of_words = int(input('Enter how many top words you want to see: '))
uniques = []
stop_words = ["a", "an", "and", "in", "is"]
for word in words:
  check_special = False
  if word.isalnum():
    check_special = True
  if word not in uniques and word not in stop_words and check_special:
    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(number_of_words, len(counts))):
  count, word = counts[i]
  print('The following words appeared %d each: %s ' % (count, word))

As a demo:

The following words appeared 11 each: night 
The following words appeared 11 each: go 

I want the demo output to be:

The following words appeared 11 each: go, night 
And in which way can I sort the words in an alphabetical order?
khelwood
  • 55,782
  • 14
  • 81
  • 108

0 Answers0