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])