Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Finding 'n' Character Words in a Text File
Next article icon

Python | Finding 'n' Character Words in a Text File

Last Updated : 04 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Using Split and List Comprehension
  • Using Regular Expressions
  • Using Generator Function

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.


Next Article
Python | Finding 'n' Character Words in a Text File

S

ssarab82
Improve
Article Tags :
  • Python
  • Python Programs
  • python-file-handling
  • Python file-handling-programs
Practice Tags :
  • python

Similar Reads

    Count Words in Text File in Python
    Our task is to create a Python program that reads a text file, counts the number of words in the file and prints the word count. This can be done by opening the file, reading its contents, splitting the text into words, and then counting the total number of words.Example 1: Count String WordsFirst,
    3 min read
    Count Vowels, Lines, Characters in Text File in Python
    We are going to create a Python program that counts the number of vowels, lines, and characters present in a given text file.Example:Assume the content of sample_text.txt is:Hello, this is a sample text file.It contains multiple lines.Counting vowels, lines, and characters.OutputTotal number of vowe
    2 min read
    Get number of characters, words, spaces and lines in a file - Python
    Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. As 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, spaces, and line
    5 min read
    Check If a Text File Empty in Python
    Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python.Check if a
    4 min read
    Find position of a character in given string - Python
    Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences