Program to find ‘n’ character word in the given text file using Python

by | Jul 28, 2021 | Python Programs

Home » Python » Python Programs » Program to find ‘n’ character word in the given text file using Python

Introduction

The task is to find four character words in the given text files.

Program to find ‘n’ character word in the given text file using Python

Program

open_file = open("demo.txt", "r") 
char = "" 
res = 1
while 1: 
    tmp = open_file.read(1) 
     if res <= 4: 
        char = char + tmp 
    if res > 4: 
        if tmp ==" ": 
            res = 0
            if len(char) > 0: 
                print(char) 
                char ="" 
        elif tmp !=" ": 
            char ="" 
    res = res + 1
 
    if not tmp: 
        break
open_file.close()

Output

Program to find ‘n’ character word in the given text file using Python Output

Explanation

The very first thing we do is that we open the file by giving the exact path of the file. Then we create a local variable “char” where we save the four character words. With the help of while loop, we will then iterate all the words of the file. Then compare the length of each word with 4. Once, there is a space read by the compiler, then the count is reset, the word is printed and the loop is reiterated until full file is read. Here, tmp is used to read the characters and res is used to count the letters.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author