0

The code below opens a text file, finds unique words (that are 5 or more chars), returns values for the number of times they appear. Is it possible to change the code so that it sorts those values highest to lowest? E.g.

great : 1
delivered : 6
safely : 12
bless : 2
states : 1

becomes:

safely : 12
delivered : 6
bless : 2
great : 1
states : 1

Code:

import string
import os

os.chdir('myfilepath') # Changes directory.

speech = open("obamaspeech.txt", "r") # Opens file.
  
emptyDict = dict() # Creates dictionary

for line in speech:
    line = line.strip() # Removes leading spaces.
    line = line.lower() # Convert to lowercase.
    line = line.translate(line.maketrans("", "", string.punctuation)) # Removes punctuation.
    words = line.split(" ") # Splits lines into words. 
    for word in words:
        if word in emptyDict: 
            emptyDict[word] = emptyDict[word] + 1
        else:
            emptyDict[word] = 1
  
for key in list(emptyDict.keys()):
    if len(key) >= 5:
        print(key, ":", emptyDict[key])
martineau
  • 119,623
  • 25
  • 170
  • 301
ck1987
  • 9
  • 2
  • Thank you for the suggestion; however, it only allows me to sort alphabetically by the key term, not numerically for the key value. – ck1987 Feb 21 '22 at 20:09
  • `dict(sorted(d.items(), key=lambda item: item[1], reverse=True))` – 001 Feb 21 '22 at 20:16
  • Thanks, I did see that - and again, I am very new to Python. I am struggling to find where I would place that line? I am also unsure if the "lambda" is a reference to something, or actual code? – ck1987 Feb 21 '22 at 20:18

0 Answers0