Question

Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed...

Help me with this Python Question

a. build_word_dictionary (filename) – This builds a word dictionary indexed by words from the file who’s filename is provided as an argument. It uses the words as keys and the count of occurrences as values. It returns the dictionary it constructed. It can use the ‘tokenize()’ function that is provided in the lecture slides.

b. inverse_dict(dict) – This method takes a dictionary (generated by build_word_dictionary() and inverts it (as was done with students and majors in the lecture slides). The count of occurrences should now be the key. The values will be a list of words that occurred that many times. This method returns a list of lists.

c. dict_to_list(dict) – This method takes the dictionary and collects the keys from the dictionary into a list. It then sorts the list in alphabetical order using Python’s sort() method. It returns the sorted list

d. dict_to_list_by_count(dict) – This method takes the inverted list (where the number of occurrences is the key and the values are lists of words). It returns the list of lists in reverse order (most frequently occurring words to least frequently occurring).

Remember that in dict_to_list_by_count(), when building the final list, you can sort the counts that you added to a list but can use them to retrieve the values (word lists) from the original dictionary to build the final list of lists you will return.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

# Here is the python code that reads from a file file.txt with comments and working screenshots

# you will have to work the indentation for yourself because HomeworkLib doesnt allow to add indentation but I can upload the file to ideone

# find it here https://ideone.com/3FSOxY

def build_word_dictionary (filename):
# this function reads from provided filename line by line (it wont take \n at the end)
  
word_dict = {} # this will store the word frequencies
with open(filename,'r') as f:
for line in f:
for word in line.split():
if word not in word_dict:
word_dict[word] = 1 # insert the word in the dict
else:
word_dict[word] += 1 # increase the count if already exists
  
return word_dict

def inverse_dict(dict):
# this function reverses the given dictionary
  
inv_dict = {}
for key,value in dict.items():
if value not in inv_dict:
inv_dict[value] = [key] # start a new list because this is the first occurence for given value
else:
inv_dict[value].append(key) # append to the already existing list for this value
  
return inv_dict

def dict_to_list(dict):
# converts keys of dictionaries to a sorted list
my_list = [key for key in dict.keys()] # create list from dict keys
return sorted(my_list) # return sorted list

def dict_to_list_by_count(dict):
# returns list of list from inverted dictionary in descending order of counts
list_of_lists = []
for key,values in sorted(dict.items())[::-1]: # this will iterate sorted dictionary in descending order
list_of_lists.append(values)
  
return list_of_lists

############## END OF FUNCTIONS

my_dict = build_word_dictionary('file.txt')
print("Output of Function 1: ", my_dict)
print()

inv_dict = inverse_dict(my_dict)
print("Output of Function 2: ", inv_dict)
print()

sorted_keys = dict_to_list(my_dict)
print("Output of Function 3: ", sorted_keys)
print()

list_of_lists = dict_to_list_by_count(inv_dict)
print("Output of Function 4: ", list_of_lists)

Jupyter HomeworkLib Last Checkpoint: 8 minutes ago (autosaved) Logout Fle dt Vew Insert Cel Kernel Widgess Help Python 3 O return inv aict 26 27 def dict to listidict): ㎎/file.txt-Sublime Text (UNREGISTERED) # converts keys of dictionaries to a sorted List ny-list- [key for key in dict, keys()] # create list from dict keys return sorted (ny list) return sorted list File Edit Selection Find View Goto Tools Project Preferences Help 29 30 31 park thestre cheag.c 1 Chegg 2 is 3 good 4 Chegg s for 6 life 7 Chegg 8 15 32 def dict to list bycount(dict) # returns list of list from inverted dictionary in descending order of List of lists for 34 key, values in sorted(dict. itens())[::-1]: list of lists.append(values) # this will iterate sort 35 36 return list of lists 38 39 49 #4弃22 4444유#** END OF FUNCTIONS 42 my dictbuild word dictionary(file.txt) 43 print(Output of Function 1: my dict) 44 print) 45 46 inv dict-Inverse dict(ny dict) 47 print(Output of Function 2: . inv dict) 48 print se sorted keys dict-to-ust (my-dict 51 printOutput of Function 3: . sorted keys) 52 print 53 54 list of listsdict to list by count(inv dict) 55 print(Output of Function 4: ist of lists) 56 Find Prev Find All Output of Function 1: Chegg: 3, is 2, good1, for: 1. ife1 WOw 1 Output af Function 2: 13: Chegg, 2: is, 1: [gaad, for, ife wow]) Output of Function 3: Chegg,for, good, is, life, wow Output af Function 4: [Chegg , Iis1, goodfor life wow1 In 1

Add a comment
Know the answer?
Add Answer to:
Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • Hey guys I need help with this question with 3 sub-problems. f test remove short synonyms () Define the remove shorti s...

    Hey guys I need help with this question with 3 sub-problems. f test remove short synonyms () Define the remove shorti synonyms function which is passed a dictionary as a parameter- The keys of the parameter dictionary are words and the corresponding values are 1ists of synonyms (synonyms are words which have the same or nearly the same meaning). The function romoves all the eynonyme which have ous than 8 charactors from each corresponding list of synonyms-As well, the funet...

  • python please 11 def add_item(items, word): 14 15 16 F # check if the word is...

    python please 11 def add_item(items, word): 14 15 16 F # check if the word is in the dictionary (keys of dictionary) if word in items: items [word] = items (word] + 1 # update the count else: # word is not in dictionary items[word] = 1 # add the word with count 1 return items [word] # return the current count of word after updation Create a function named build_dictionary that takes a list of words (as a parameter)...

  • In python Count the frequency of each word in a text file. Let the user choose...

    In python Count the frequency of each word in a text file. Let the user choose a filename to read. 1. The program will count the frequency with which each word appears in the text. 2. Words which are the spelled the same but differ by case will be combined. 3. Punctuation should be removed 4. If the file does not exist, use a ‘try-execption’ block to handle the error 5. Output will list the words alphabetically, with the word...

  • Hey guys I need help with this assignment. However it contains 7 sub-problems to solve but I figured only 4 of them can...

    Hey guys I need help with this assignment. However it contains 7 sub-problems to solve but I figured only 4 of them can be solved in one post so I posted the other on another question so please check them out as well :) Here is the questions in this assignment: Note: Two helper functions Some of the testing codes for the functions in this assignment makes use of the print_dict in_key_order (a dict) function which prints dictionary keyvalue pairs...

  • In python, PART A: I am trying to get a dictionary with size(4, 5, 6) as...

    In python, PART A: I am trying to get a dictionary with size(4, 5, 6) as keys and an array for key containing a list of values (words from file of respective size) associated with those keys I am reading from a file of strings, where I am only interested with words of length 4, 5, and 6 to compute my program reading the text file line by line: At first, I have an empty dictionary then to that I...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • Define the functions in Python 3.8 1. Write a function most frequent n that takes a...

    Define the functions in Python 3.8 1. Write a function most frequent n that takes a list of strings and an integer n, and that returns a dictionary where the keys are the top n most frequent unique words in the list, and the values are the frequency of each word: For example, most frequent n(text, 3) should return the dictionary {'is': 2, "the’: 3, 'of': 2}, and most frequent n(text, 2) could return either {'is': 2, 'the’: 3} or...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • can someone please help me write a python code for this urgently, asap Question: Write a Python function, minmp,...

    can someone please help me write a python code for this urgently, asap Question: Write a Python function, minmp, that is passed a file name and a metal alloy's formula unit structure*". The file will contain metal elements and their properties. The function will return a tuple of the element from the formula with the lowest melting point and that melting point Write a second function, molform, that will be called by the first function, to take the metal alloy's...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT