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 :-

Note :- I have made this program for both TXET file and Binary file.

For Text file :

def Show_words():
      f = open("notes.txt","r")
      data = f.readlines()
      for i in data :
          words = i.split()
          if len(words) == 5 :
              print(i)
      f.close()
      
Show_words()

For binary file :- 

import pickle

def Show_words():
      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()
Show_words()
 

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.

>>>

5 Comments

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

  1. This is for binary file and the question is asked for text file

    ReplyDelete
    Replies
    1. Ok, I have made this program for both TXET file and Binary file.

      Delete
  2. But only those lines must be printed which have 5 words...

    ReplyDelete
  3. Thank you so much

    ReplyDelete

Post a Comment

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

Previous Post Next Post