The task is to find four character words in the given text files.
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()
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.