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')
  for i in
    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 // JNCIE-SEC #223 / RHCE / PCNSE

You have a feedback?

Discover more from

Subscribe now to keep reading and get access to the full archive.

Continue reading