book_name is the war and peace txt file call: War_and_Peace_no_punc.txt from pro
ID: 3713584 • Letter: B
Question
book_name is the war and peace txt file call:
War_and_Peace_no_punc.txt from project gutenberg
When writing dictify, we need to account for the ' ' characters at the end of certain words.
So we need to get these new values :
{6: 48342, 15: 254, 23: 2} this is only part of the solution
Your challenge for this problem is to create a function dictify that takes in 1 argument: book_name. book_name: the string that is the name of the file to opern return: a dictionary containing the count of each length of word in sorted order. Eg. How many words total of length 1, 2, 3...? Your output should look like (we cut out most of the dictionary): (6: 48342, 15: 254, 23: 2) Hints: Read in files using infile-open (filename), make sure that you are in the same directory. . Read each line by looping through with a simple for loop Split the lines using line.split(" "), to get a list of the words Since the book is long and complex, you might get zero length words (some tabs and spaces). Make sure to filter those out of your dictionary! Your output dictionary should have its keys in sorted order, so [1: xxxx, 2: xxxxx, 3: xxxxx..Explanation / Answer
#dictify function
def dictify(filename):
#oopening the file
File = open(filename,'r')
#temporary dictionary
Dict = {}
#setting all values to 0
for i in range(0,30):
Dict[i]=0
#reading lines in file
for line in File:
#splitting the words
words=line.split(' ');
#evaluating the word
for word in words:
#fincding the length
key = len(word)
#if the word is valid
if(key!=0):
#incrementing the count of the length
Dict[key] = Dict[key]+1;
#new dictionary without the 0 count elements data
NewDict = {i:Dict[i] for i in Dict if Dict[i]!=0}
#returning the new resultant dictionary
return NewDict
#main program to test the code
def main():
#reading the file name
filename=input("Entr file name ::")
#getting the data
data = dictify(filename)
#printing the data
print(data)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.