I created a dictionary that counts the number of occurrences of each word in a separate text file. So far it looks like this.
import sys
def main():
d = dict({})
with open(sys.argv[1], encoding="utf-8") as f:
for line in f:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in list(d.keys()):
print(key, ":", d[key])
if __name__ == "__main__":
main()
In the command line, I input a text file for it to count the frequencies of each word (executing "python3 frequencycount.py example.txt"). This code effectively executes a list of all words in the text file and it counts how many times they occur. What I'm trying to do now is print the words in descending order by frequency of occurrence.
For example, my text file is a list of vegetables (pepper 5 times, carrot 9 times, peas 8 times, and broccoli 1 time). The list looks like this:
Pepper : 5
Carrot : 9
Peas : 8
Broccoli : 1
However, I would want it to print like this:
Carrot : 9
Peas : 8
Pepper : 5
Broccoli : 1
How can I make it print in descending order like this? Thanks.