In python please: A useful application for a dictionary is to remember, or cache
ID: 3758764 • Letter: I
Question
In python please:
A useful application for a dictionary is to remember, or cache, previously obtained results so that they can be retrieved from the cache when they are requested anew. Modify the program in the programming that is below, so that the user can repeatedly enter filenames. If the user enters the same filename more than once, look up the answer from a dictionary instead of counting the words again.
Programming that needed to use:
# IMPORTS
from sys import argv
# FUNCTIONS
def clean(string):
output_string = ""
for char in string:
if char.isalpha():
output_string += char
return output_string.lower()
def count_words(filename):
output_dictionary = {}
with open(filename, "r") as file:
for line in file:
words = line.split()
word_times = 1
for word in words:
word = clean(word)
if word in output_dictionary:
word_times += 1
output_dictionary[word] = word_times
return output_dictionary
def print_dictionary(dictionary):
for key in sorted(dictionary):
print("{}: {}".format(key, dictionary[key]))
# main
def main():
words = count_words(argv[1])
print_dictionary(words)
# PROGRAM RUN
if __name__ == "__main__":
main()
Explanation / Answer
you just need to change the main for this.
new main will be
def main():
for filename in sys.argv[1:]:
words = count_words(filename)
print_dictionary(words)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.