Python File Word Count using Dictionary

  • Post author:
  • Post last modified:February 27, 2018
  • Post category:General
  • Reading time:2 mins read

Dictionaries are one of the best data types introduced in the Python. The dictionary holds data in form on Key:value pair. In this article, will present you the solution to Python File Word Count using Dictionary.

Text File

Acquire the text file from which you want to count repetition of each and every word. For the testing purpose, create any file with some of your favourite story or anything.

Python File Word Count using Dictionary

Let’s work step by step on building this game. In this program, we are going to create a function. The function accepts the file name as an parameter.

def word_count(f):
 #Create empty dictionary. This will store the words and its count
 d = dict()

# open file for reading
 fl = open(f)

# read file to an variable
 fl1 = fl.read()

# split each word based on the ' ' (space) 
 for c in fl1.split(' '):
 if c not in d:
 d[c] = 1
 else:
 d[c] += 1
 return d

Above function will return dictionary with words and its count in for of key:value .

Call Function by Passing Parameter

Call the function and assign results to variable.

word_cnt = count_word('text.txt')
word_cnt_sorted = sorted(h.items(), key=lambda x:x[1],reverse=True)
print word_cnt_sorted