Top 5 Easy Methods: Count Words in File Python

How to Count Words in File Python:

In this program, Count the Number of  words in the text file using Python. This is also done by opening the file in reading mode using text file. Read the file line by line. Split the line at a time and stored in an array file. Iterate through the array file and count word.The paragraph of sample.txt file used in the example is shown below.

 

Sample Text File:

Welcome to www.pythonexamples.org. Here, you will find more python programs of all easy and avanced.
This is another line with some words.Random Numbers 544 124 357

 

Example #1:

fname = input("Enter file name: ")
num_words = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)
print(f"Total Number of words: {num_words}")

OUTPUT

Enter file name: sample.txt
Total Number of words: 25

 

Example #2:

number_of_words = 0
 
with open(r'SampleFile.txt','r') as file:
    data = file.read()
    lines = data.split()
    number_of_words += len(lines)
 
print(f'Total Number of Words: {number_of_words}')

OUTPUT

Total Number of Words: 25

 

Example #3: Only Count words in File, not Integer

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(f'Total Number of Words: {number_of_words}')

OUTPUT

Total Number of Words: 22

 

Example #4:

file = open("sample.txt", "rt")
data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

OUTPUT

Number of words in text file : 25

 

Example #5:

with open("sample.txt",'r') as f:
    words = [word for line in f
             for word in line.strip().split()]
print(f"Number of words: {len(words)}")

 

OUTPUT

Number of Words: 25