Python Program to Count Words in Text File
Last Updated :
15 Dec, 2021
In this article, we are going to see how to count words in Text Files using Python.
Example 1: Count String Words
First, we create a text file of which we want to count the number of words. Let this file be SampleFile.txt with the following contents:
File for demonstration:
Below is the implementation:
Python3
number_of_words = 0
with open (r 'SampleFile.txt' , 'r' ) as file :
data = file .read()
lines = data.split()
number_of_words + = len (lines)
print (number_of_words)
|
Output:
7
Explanation:
- Creating a new variable to store the total number of words in the text file. And then open the text file in read-only mode using the open() function.
- Read the content of the file using the read() function and storing them in a new variable. And then split the data stored in the data variable into separate lines using the split() function and then storing them in a new variable. And add the length of the lines in our number_of_words variable.
Example 2: Count the number of words, not Integer
File for demonstration:
Below is the implementation:
Python3
number_of_words = 0
with open (r 'SampleFile.txt' , 'r' ) as file :
data = file .read()
lines = data.split()
for word in lines:
if not word.isnumeric():
number_of_words + = 1
print (number_of_words)
|
Output:
11
Explanation: Create a new variable to store the total number of words in the text file and then open the text file in read-only mode using the open() function. Read the content of the file using the read() function and storing them in a new variable and then split the data stored in the data variable into separate lines using the split() function and then storing them in a new variable, Iterating over every word in lines using the for loop and check if the word is numeric or not using the isnumeric() function then add 1 in our number_of_words variable.
Share your thoughts in the comments
Please Login to comment...