Q. Write a function Show_words() in python to read the content of a text file "NOTES.TXT" and display only such lines of the file which have exactly 5 words in them.

Example, if the file contains :

This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.

Then the function should display the output as :

This is a sample file.

The file contains many sentences.

Answer :-

import pickle

f = open("NOTES.dat", "rb")

try :
    while True:
        line = pickle.load(f)
        word = line.split()
        if len( word ) == 5 :
            print( line )
except EOFError:
    f.close()
 

Output :-

For output in your device at first you have to write data in .dat file by following code :-

import pickle

f = open("NOTES.dat", "wb")
pickle.dump("This is a sample file.",f)
pickle.dump("The file contains many sentences.", f)
pickle.dump("But need only sentences which have only 5 words.", f)
pickle.dump("", f)
pickle.dump("My Website is Path Walla.", f)
pickle.dump("I used to upload solutions of books.", f)
pickle.dump("I love Python.", f)
pickle.dump("", f)

f.close()

Then write this code :-

import pickle

f = open("NOTES.dat", "rb")

try :
    while True:
        line = pickle.load(f)
        word = line.split()
        if len( word ) == 5 :
            print( line )
except EOFError:
    f.close()

Then output is :-

This is a sample file.
The file contains many sentences.
My Website is Path Walla.

>>>

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post