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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!