Reading File: Word By Word
Question: 1
Python program to read the contents of the file “abc.txt” word by word and display the contents.
Sol:
Method:1
def read_words(): with open("abc.txt") as f: for line in f: for word in line.split(): print(word) #function calling read_words()
Method:2
def read_words(): with open("abc.txt") as f: for line in f: for word in line.split(): print(word) #function calling read_words()
Question: 2
Python program 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 count_words(): w=0 with open("abc.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()
Method:2
def count_words(): w=0 with open("abc.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
Python program to read the contents of the file “abc.txt” word by word and display the contents. and also display the total number of words starting with “a” or “A” in the file.
Sol:
Method:1
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
Python program to read the contents of the file “abc.txt” word by word and display the contents. and also display the 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()
Question: 5
Python program to read the contents of the file “abc.txt” word by word and display the contents. and also display the total number of words not 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 not(word[0]=="a" or word[0]=="A"): print(word) w=w+1 print("total words not starting with 'a' are ",w) function calling count_words()