''' DS2000 Spring 2022 Sample code from class - word frequencies in NEU announcments ''' NEU_FILE = "neu_announcements.txt" def read_txt(filename): ''' Function: read_txt Parameter: filename, a string Returns: a list of strings, one per row in the file ''' lst = [] with open(filename, "r") as infile: while True: word = infile.readline() if word == "": break word = word.strip() lst.append(word) return lst def wordcount(lst): ''' Function: wordcount Parameter: list of words returns: dictionary where key - word, value - freuency of that word ''' wc = {} for word in lst: if word in wc: wc[word] += 1 else: wc[word] = 1 return wc def max_word(count_dct): ''' Function: max_word parameter: dictionary where key - string, value - num of occurrences returns: a tuple (key, value) for the highest value in the dictionary ''' max_key = "" max_value = -1 for key, value in count_dct.items(): if value > max_value: max_value = value max_key = key return (max_key, max_value) def main(): # Step one: gather data -- read from the file into a list words = read_txt(NEU_FILE) # Step two: computation -- count the frequency # of each word wc = wordcount(words) # get the max word word, count = max_word(wc) # step three: communicate! # report the max word and its count print(word, "was written the most,", count, "times!") word = input("What word to look for?\n") count = wc[word] print(word, "was said", count, "times") main()