Finding the frequency of words in a file with python
If you want to find how many times a single word is repeated in a file, I have quoted my code below. The method that I didn’t know before was the “get” method. It allows you to get the value of the key but if it isn’t set before, set the value specified in our example 0. This allows us to count the occurrence indeed.
def count_words(filename): f = open(filename,'r') words_dict={} for i in f.read().split(): word=i.lower() words_dict[word]= words_dict.get(word,0) + 1 for key in words_dict.keys(): print str(key)+' = '+str(words_dict[key])