Open In App

Python Program to Count Words in Text File

Last Updated : 15 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




# creating variable to store the
# number of words
number_of_words = 0
 
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt','r') as file:
 
    # Reading the content of the file
    # using the read() function and storing
    # them in a new variable
    data = file.read()
 
    # Splitting the data into separate lines
    # using the split() function
    lines = data.split()
 
    # Adding the length of the
    # lines in our number_of_words
    # variable
    number_of_words += len(lines)
 
 
# Printing total number of words
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




# creating variable to store the
# number of words
number_of_words = 0
 
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt','r') as file:
 
    # Reading the content of the file
    # using the read() function and storing
    # them in a new variable
    data = file.read()
 
    # Splitting the data into separate lines
    # using the split() function
    lines = data.split()
 
    # Iterating over every word in
    # lines
    for word in lines:
 
        # checking if the word is numeric or not
        if not word.isnumeric():         
 
            # Adding the length of the
            # lines in our number_of_words
            # variable
            number_of_words += 1
 
# Printing total number of words
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.



Previous Article
Next Article

Similar Reads

Python Program to Find the Number of Unique Words in Text File
Given a text file, write a python program to find the number of unique words in the given text file in Python. Examples: Input: gfg.txt Output: 18 Contents of gfg.txt: GeeksforGeeks was created with a goal in mind to provide well written well thought and well explained solutions for selected questions Explanation: Frequency of words in the file are
2 min read
Python | Scramble words from a text file
Given some data in a text file, the task is to scramble the text and output in a separate text file. So, we need to write a Python program that reads a text file, scrambles the words in the file and writes the output to a new text file. Rules to be followed: Words less than or equal to 3 characters need not be scrambled.Don't scramble first and las
3 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 the of length 3 from the input file.Input File: File
3 min read
How to Use Words in a Text File as Variables in Python
We are given a txt file and our task is to find out the way by which we can use word in the txt file as a variable in Python. In this article, we will see how we can use word inside a text file as a variable in Python. Example: Input: fruits.txt apple banana orange Output: apple = Fruit banana = Fruit orange = Fruit Explanation: Here, we are using
3 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Python program to Count the Number of occurrences of a key-value pair in a text file
Given a text file of key-value pairs. The task is to count the number of occurrences of the key-value pairs in the file with Python Program to Count the occurrences of a key-value pairNaive Approach to Count the Occurrences of a key-value PairUsing Python built-in collections.CounterUsing regular expressions (re module)Text file: Naive Approach to
3 min read
Python program to count the number of blank spaces in a text file
All programs need input to process and after processing gives the output. Python support file handling and allow user to handle files. The concept of file handling has stretched over various other languages, But the implementation is either lengthy or complicated. Python treats file differently as text and binary,One thing to note while writing dat
3 min read
Python Program to Count Vowels, Lines, Characters in Text File
In this article, we are going to create a python program that counts vowels, lines, and a number of characters present in a particular text file. ApproachWe have to open the file using open() function in python.Then make three variables, vowel, line and character to count the number of vowels, lines, and characters respectively.Make a list of vowel
2 min read
Python - Count occurrences of each word in given text file
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 increm
4 min read
Practice Tags :
three90RightbarBannerImg