Class XII: Python Data File Handling 7

File reading: Word by word

Question:1
write a (python script) function named read_words() to read the contents of the file “abc.txt” word by word and display the contents.
Sol:

Method:1

def read_words():
    with open("file1.txt") as f:
      while True:
        d=f.readline()
        if not d:
          break
        for word in d.split():
            #for word  in line.split():
          print(word)
#function calling
read_words()

Method:2

def read_words():
    with open("file1.txt") as f:
        for line in f:
            for word  in line.split():
                print(word)
#function calling
read_words()

Question:2
write a (python script) function named count_words() to read the contents of the file “abc.txt” word by word and display the contents. and also display total words in the file.
Sol:

Method 1

def read_words():
  c=0
  with open("file1.txt") as f:
    while True:
      d=f.readline()
      if not d:
        break
      for word in d.split():
        #for word  in line.split():
        print(word)
        c=c+1
    print('no of words=',c)
#function calling
read_words()

Method 2

def count_words():
     w=0
     with open("file1.txt") as f:
         for line in f:
             for word  in line.split():
                 print(word)
                 w=w+1
         print("total words ",w)
 #function calling
 count_words()

Question:3
write a (python script) function named count_words() to read the contents of the file “abc.txt” word by word and display the contents. and also display total number of words starting with “a” or “A” in the file.
Sol:

def count_words():
    w=0
    with open("abc.txt") as f:
        for line in f:
            for word  in line.split():
                if(word[0]=="a" or word[0]=="A"):
                    print(word)
                    w=w+1
        print("total words starting with 'a' are ",w)
#function calling
count_words()

Question:4
write a (python script) function named count_words() to read the contents of the file “abc.txt” word by word and display the contents. and also display total number of words starting with tarting with vowels “a”,”e”,”i”,”o”,”u” or “A” ,”E”,”I”,”O”,”U”
Sol:

def count_words():
     w=0
     vowels="aeiouAEIOU"
     with open("abc.txt") as f:
         for line in f:
             for word  in line.split():
                 if(word[0] in vowels):
                     print(word)
                     w=w+1
         print("total words starting with vowels are ",w)
 #function calling
 count_words()