Python - Count occurrences of each word in given text file
Last Updated :
25 Aug, 2022
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the word is already present in the dictionary we increment its count by 1.
File sample.txt
First, we create a text file in which we want to count the words in Python. Let this file be sample.txt with the following contents
Mango banana apple pear
Banana grapes strawberry
Apple pear mango banana
Kiwi apple mango strawberry
Example 1: Count occurrences of each word in a given text file
Here, we use a Python loop to read each line, and from that line, we are converting each line to lower for the unique count and then split each word to count its number.
Python3
# Open the file in read mode
text = open("sample.txt", "r")
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in text:
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
Output:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
Example 2: Count occurrences of specific words in a given text file
In this example, we will count the number of "apples" present in the text file.
Python3
word = "apple"
count = 0
with open("temp.txt", 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
count=count+1
print("Occurrences of the word", word, ":", count)
Output:
Occurrences of the word apple: 2
Example 3: Count total occurrences of words in a given text file
In this example, we will count the total number of words present in a text file.
Python3
count = 0
# Opens a file in read mode
f = open("sample.txt", "r")
# Gets each line till end
for line in f:
# Splits into words
word = line.split(" ")
# Counts each words
count += len(word)
print("Total Number of Words: " + str(count))
f.close()
Output:
Total Number of Words: 15
Consider the files with punctuation
Sample.txt:
Mango! banana apple pear.
Banana, grapes strawberry.
Apple- pear mango banana.
Kiwi "apple" mango strawberry.
Code:
Python3
import string
# Open the file in read mode
text = open("sample.txt", "r")
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in text:
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Remove the punctuation marks from the line
line = line.translate(line.maketrans("", "", string.punctuation))
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, " ", d[key])
Output:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
Similar Reads
Python - Occurrence counter in List of Records Sometimes, while dealing with records we can have a problem in which we need count the occurrence of incoming digits corresponding to different characters/players in a game and compile them in a dictionary. This can have application in gaming and web development. Lets discuss a way in which this can
2 min read
Count Words in Text File in Python Our task is to create a Python program that reads a text file, counts the number of words in the file and prints the word count. This can be done by opening the file, reading its contents, splitting the text into words, and then counting the total number of words.Example 1: Count String WordsFirst,
3 min read
Python program to find occurrence to each character in given string Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them. Method #1: Using set() + count() Iterate over the set converted string and get the count
5 min read
Python | Count occurrence of all elements of list in a tuple Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Appro
5 min read
Python | Finding 'n' Character Words in a Text File This article aims to find words with a certain number of characters. In the code mentioned below, a Python program is given to find the words containing three characters in the text file. Example Input: Hello, how are you ? , n=3 Output: how are you Explanation: Output contains every character of th
3 min read