In: Computer Science
Python class
Select a free ebook and download the plain text file (utf8).
Write a program that does the following:
Turn in a .py or Google Colab URL
Dictionaries are not easily sortable since they are not ordered like a list. To sort for this assignment use the following template.
import operator
sorted_dict =
sorted(my_dict.items(),key=operator.itemgetter(1))
CODE:
RAW CODE:
import operator
file = open("file","r") # opening a file in read mode , replace file name with your own file
data = file.read().split() # reading all data and split the data into words using by split() function
dic = {} # empty dic
for word in data: # iterate each word in data
if word not in dic: # if the word is not present in the dic than add new pair with (word,1) as key and value
dic[word] = 1
else: # if the word is already exists in the dic than increment the value of dic[word]
dic[word] = dic[word] + 1
sorted_dict = sorted(dic.items(),key=operator.itemgetter(1)) # sorting dictionary based on value
out = open("freqs.txt","w") # opening file in write mode
for item in sorted_dict: # iterate each item(tuple) in sorted_dict
out.write(str(item[0]) + "\t:" + str(item[1]) + "\n") # write the item data(key and value) into txt file. key = item[0] , value = item[1]
# closing files
file.close()
out.close()
NOTE:
If You have any doubts feel free to comment in comment
section.
DO VOTE(LIKE).