Question
Write a function called count_words. This function is passed the name of a file, and should count the number of times each word occurs in
Write a function called count_words. This function is passed the name of a file, and should count the number of times each word occurs in the file. A dictionary should be returned, whose keys are words, and whose values are their counts. For example:
>>> freq = count_words('hamlet.txt') >>> freq['to'] 13
>>> freq['be'] 3 >>> freq['or'] 2
>>> freq['hamlet']
Traceback (most recent call last): File "", line 1, in
freq['hamlet'] KeyError: 'hamlet'
hamlet txt below
to be or not to be that is the question whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune or to take arms against a sea of troubles and by opposing end them to die to sleep no more and by a sleep to say we end the heartache and the thousand natural shocks that flesh is heir to tis a consummation devoutly to be wished to die to sleep to sleep, perchance to dream ay there is the rub for in that sleep of death what dreams may come when we have shuffled off this mortal coil must give us pause there is the respect that makes calamity of so long life
python 2.7.13 shell
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started