The Wayback Machine - https://web.archive.org/web/20240926154201/https://www.geeksforgeeks.org/python-finding-n-character-words-in-a-text-file/
Open In App

Python | Finding ‘n’ Character Words in a Text File

Last Updated : 04 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: File1.txt

Finding 'n' Character Words in a Text File

File1.txt

Python Program to Find ‘n’ Character Words in a Text File

Below are the methods that we will cover in this article:

Finding a Given Word in Text File using Split and List Comprehension

You can read the file, split its content into words, and then filter out words with ‘n’ characters using list comprehension.

PYTHON




def find_words_with_three_chars(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        words = content.split()
 
        words_with_three_chars = [word for word in words if len(word) == 3]
 
        return words_with_three_chars
 
file_name = "File1.txt"
result = find_words_with_three_chars(file_name)
 
print("Words containing three characters:")
print(result)


Output:

Words containing three characters: ['sit', 'sed', 'sit', 'ac.', 'dui', 'sit']

Time Complexity: O(N), where N is the total number of characters in the file.
Space Complexity: O(N + M), where M is the number of words with ‘n’ characters in the file.

Search a given word in a Text File using Regular Expressions

In Python, we have re module which provides regular expression functionality. The Regular expressions can be used to match patterns in the text which allows you to find words with ‘n’ characters.

Python3




import re
 
def find_n_character_words(file_path, n):
    with open(file_path, 'r') as file:
        content = file.read()
 
    # Use regular expression to find words with 'n' characters
    pattern = r'\b\w{' + str(n) + r'}\b'
    words_with_n_chars = re.findall(pattern, content)
 
    return words_with_n_chars
 
file_name = "File1.txt"
n = 3
result = find_n_character_words(file_name, n)
 
print(f"Words containing {n} characters:")
print(result)


Output:

Words containing 3 characters:
['sit', 'sed', 'sit', 'dui', 'sit']

Time Complexity: O(N), where N is the total number of characters in the file.
Space Complexity: O(N)

Get Words Containing three Characters in the File using Generator Function

Here you can use a generator function to yield words with ‘n’ characters one by one. This can be useful for large files.

Python3




def generate_n_character_words(file_path, n):
    with open(file_path, 'r') as file:
        for line in file:
            for word in line.split():
                if len(word) == n:
                    yield word
 
file_name = "File1.txt"
n = 3
result_generator = generate_n_character_words(file_name, n)
 
print(f"Words containing {n} characters:")
for word in result_generator:
    print(word)


Output:

Words containing 3 characters:
sit
sed
sit
dui
sit

Time Complexity: O(N), where N is the total number of characters in the file.
Space Complexity: O(M), where M is the number of words with ‘n’ characters in the file.



Similar Reads

Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 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
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
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.txtOutput: 18Contents of gfg.txt: GeeksforGeeks was created with a goal in mind to provide well written well thought and wellexplained solutions for selected questionsExplanation:Frequency of words in the file are {'ge
2 min read
Python Program to Count Words in Text File
In this article, we are going to see how to count words in Text Files using Python. Example 1: Count String WordsFirst, 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:[GFGTABS] Python # creating variable to store the
3 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Scraping And Finding Ordered Words In A Dictionary using Python
What are ordered words? An ordered word is a word in which the letters appear in alphabetic order. For example abbey & dirt. The rest of the words are unordered for example geeks The task at hand This task is taken from Rosetta Code and it is not as mundane as it sounds from the above description. To get a large number of words we will use an onlin
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
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
Finding the largest file in a directory using Python
In this article, we will find the file having the largest size in a given directory using Python. We will check all files in the main directory and each of its subdirectories. Modules required: os: The os module in Python provides a way of using operating system dependent functionality. OS module is available with Python's Standard Library and does
2 min read
Python - Group Similar Start and End character words
Sometimes, while working with Python data, we can have problem in which we need to group all the words on basis of front and end characters. This kind of application is common in domains in which we work with data like web development. Lets discuss certain ways in which this task can be performed. Method #1 : Using defaultdict() + loop The combinat
5 min read
PyQt5 - Finding the item through text in ComboBox
In this article we will see how we can find the item index with the help of text in it. We know we can add items with the help of addItems method, in order to find the item with the help of findText method. Syntax : combo_box.findText(text) Argument : It takes string as argument. Return : It return integer i.e index of text if text doesn't exist it
2 min read
Python - Get number of characters, words, spaces and lines in a file
Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. Python - Get number of characters, words, spaces and lines in a fileAs we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to calculate the total number of characters, words
5 min read
Python | Insert character after every character pair
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
6 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
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 - 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
Python | Create an empty text file with current date as its name
In this article, we will learn how to create a text file names as the current date in it. For this, we can use now() method of datetime module. The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute
1 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 program to Reverse a single line of a text file
Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer science portal User choice = 0 Output: geek a is This
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
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
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
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
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