The Wayback Machine - https://web.archive.org/web/20240822193246/https://www.geeksforgeeks.org/python-program-to-count-words-in-text-file/
Open In App

Python Program to Count Words in Text File

Last Updated : 15 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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 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
Count number of lines in a text file in Python
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output: 3 Explanation: The Input has 3 number of line in
3 min read
Count the number of times a letter appears in a text file in Python
In this article, we will be learning different approaches to count the number of times a letter appears in a text file in Python. Below is the content of the text file gfg.txt that we are going to use in the below programs: Now we will discuss various approaches to get the frequency of a letter in a text file. Method 1: Using the in-built count() m
3 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks review-team@geeksforgeeks.org review-team@geeksforgeeks.org GfG is a portal for gee
1 min read
Python Program to Replace Text in a File
In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text. Method 1: Removing all text and write new text in the same file In this method we replacing a
3 min read
Python program to reverse the content of a file and store it in another file
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types. Full reversing: In this type of reversing all the content gets reversed. Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last position.
2 min read
Change the color of certain words in the tkinter text widget
Python has various options for Graphical User Interface (GUI) development. One of the options is Tkinter. Tkinter and Python together provide a faster way for GUI development. The Tk GUI toolkit provides an object-oriented interface. For creating GUI applications using Tkinter we have to follow a few steps – Import Tkinter module.Create the main wi
3 min read
Convert Text Image to Hand Written Text Image using Python
In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python. Module needed: Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To
2 min read
Python: Convert Speech to text and text to Speech
Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction on how to make use of the SpeechRecognition and pyttsx3 library of Python.Installation required: Python Speech Recognition module: pip install speechrecognitionPyAudio: Use the f
3 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Python - Append content of one text file to another
Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python. Append the content of one text file to anotherUsing file objectUsing shutil moduleUsing fileinput moduleSuppose the text files file1.txt and file2.txt contain the following data. file1.txt file2.txt Append the c
3 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
Pulling a random word or string from a line in a text file in Python
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python's random module to pick a random word. There are various ways to perform this operation: This is the text file we will read from: Method 1: Using rando
2 min read
Python - Create Graph from Text File
Matplotlib library in Python is a very popular data visualization library. Different graphs can be plotted from this library such as bar plot, pie plot, histogram, scatter plot, line plot, etc. The source of data can be any file like CSV(Comma Separated File), text file, etc. In this article, Graphs are created based on the data taken from a text f
3 min read
How to remove brackets from text file in Python ?
Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions. Syntax: # import re module for using regular expression import re patn = re.sub(pattern, repl, sentence) # pattern is the special RE expression for fin
3 min read
How to search and replace text in a file in Python ?
In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents: To r
5 min read
How to Read Text File Into List in Python?
In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of t
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
Create a New Text File in Python
Creating a new text file in Python is a fundamental operation for handling and manipulating data. In this article, we will explore three different methods to achieve this task with practical examples. Whether you're a beginner or an experienced developer, understanding these methods will provide you with the flexibility to work with text files in P
2 min read
Create a Nested Dictionary from Text File Using Python
We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dictionary From Text File using Python: Using json.lo
3 min read
Detect Encoding of a Text file with Python
Python provides a straightforward way to determine the encoding of a text file, essential for the proper handling of diverse character sets. The chardet library is a popular choice for automatic character encoding detection. By analyzing the statistical distribution of byte values, it accurately identifies the encoding scheme used in a given text f
2 min read
Convert PDF File Text to Audio Speech using Python
Let us see how to read a PDF that is converting a textual PDF file into audio. Packages Used: pyttsx3: It is a Python library for Text to Speech. It has many functions which will help the machine to communicate with us. It will help the machine to speak to usPyPDF2: It will help to the text from the PDF. A Pure-Python library built as a PDF toolkit
2 min read
Replace Commas with New Lines in a Text File Using Python
Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file. Replace Comma With a New Line in a Text FileBelow are the possible approaches to rep
2 min read
Practice Tags :
three90RightbarBannerImg