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])


About: rtoodtoo

Worked for more than 10 years as a Network/Support Engineer and also interested in Python, Linux, Security and SD-WAN, currently living in the Netherlands and works as a Network Support Engineer. // JNCIE-SEC #223 / RHCE / PCNSE


You have a feedback?

This site uses Akismet to reduce spam. Learn how your comment data is processed.