0

So I have the code below to count the number of words in a text file. I'd like to sort the output of this by words that appeared the greatest number of times to words that appeared the least number of times. How can this be accomplished?

ally = open("alice.txt", "r")
wordcount={}
for word in ally.read().split():
    if word not in wordcount:
        wordcount[word] = 1

    else:
       wordcount[word] += 1

for k,v, in wordcount.items():
    print(k,v)
e1v1s
  • 365
  • 6
  • 18

3 Answers3

2

Simply use Counter. It will both shorten your code and get you the ordering that you want.

Quoting from the documentation:

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0
armatita
  • 12,825
  • 8
  • 48
  • 49
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

You can view the sorted dictionary using operator.itemgetter():

from operator import itemgetter

wordcount = {'test': 1, 'hello': 3, 'test2':0}

sortedWords = sorted(wordcount.items(), key=itemgetter(1), reverse = True)

Output:

>>> sortedWords
[('hello', 3), ('test', 1), ('test2', 0)]
Farhan.K
  • 3,425
  • 2
  • 15
  • 26
0

This should do it for you:-

ally = open("alice.txt", "r")
wordcount={}
for word in ally.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
       wordcount[word] += 1

for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True):
    print(k,v)