Counting Occurrence of Words in a Text File

tags: #python/documentation/dictionaries

This is very similar to how we would use dictionaries to count the number of occurrences of elements/items in a sequence (e.g., word or list).

Summary of Steps

  1. Use a For Loop to read through each line of text
  2. Use the split() method to break each line into a list of words
  3. Loop for each list of words (i.e., each line) and count each word using a dictionary

Sample:

# 1. Opening text file

fname = input('Enter file name: ')
try:
	file = open(fname)
except:
	print('Invalid file name')



# 2. creating empty dictionary as counter

count = dict()

for line in file: # for each line in the text file
	line = line.rstrip() # removing whitespace and double spacing effect
	words = line.split() # creating list of words
	for word in words: # counting words and appending it to dict
		if word not in count:
			count[word] = 1
		else:
			count[word] = count[words] + 1

print(count)
Powered by Forestry.md