I have a .txt file that I am looking to return the count of each time a word appears in it. I got the code to work, but now I want to refine down to only returning words that are 5 or more characters long. I added in "len" function to a for statement, but it is still returning all words. Any help would be greatly appreciated.
I also am wondering if it is possible for me to sort by key count, to return the words with highest counts first.
import string
import os
os.chdir('mydirectory') # 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 len(word) >= 5 in emptyDict:
emptyDict[word] = emptyDict[word] + 1
else:
emptyDict[word] = 1
for key in list(emptyDict.keys()):
print(key, ":", emptyDict[key])