Test Index

CBSE Class 12 Computer Science 2025 Paper Set 4 Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 29 of 37
Marks: +1, -0
(a) Write a Python function that displays all the lines containing the word 'vote' from a text file "Elections.txt". For example, if the file contains :
In an election many people vote to choose their representative.
The candidate getting the maximum share of votes stands elected.
Normally, one person has to vote once.
The process of voting may vary with time and region.
Then the output should be :
In an election many people vote to choose their representative.
Normally, one person has to vote once.
OR
(b) Write a Python function that displays all the words starting and ending with a vowel from a text file "Report.txt". The consecutive words should be separated by a space in the output. For example, if the file contains :
Once there was a wise man in a village.
He was an awesome story-teller.
He was able to keep people anchored while listening to him.
Then the output should be :
Once a a awesome able
Solution:  
(a)
Concept: Read the file line by line, split each line into words with split() and print the line if the word 'vote' is one of its words. Checking the list of words (not the substring) makes sure that 'votes' and 'voting' are not counted as 'vote'.
def ShowVote():
F = open("Elections.txt", "r")
for line in F: # one line at a time
words = line.split() # list of words of the line
if 'vote' in words: # whole word 'vote' present
print(line, end='') # line already ends with newline
F.close()
ShowVote()
Explanation:
Line 1 has the word 'vote' and line 3 has 'vote' → both are printed. Line 2 has only 'votes' and line 4 only 'voting', so they are skipped. Output:
In an election many people vote to choose their representative.
Normally, one person has to vote once.
OR (b)
Concept: Read the whole text, split it into words and print every word whose first character w[0] and last character w[-1] are both vowels, with end=' ' so that the words come on one line separated by a space.
def VowelWords():
F = open("Report.txt", "r")
words = F.read().split() # all words of the file
F.close()
vowels = "aeiouAEIOU"
for w in words:
if w[0] in vowels and w[-1] in vowels:
print(w, end=' ')
print()
VowelWords()
Explanation:
Once (O…e), a, a, awesome (a…e) and able (a…e) start and end with a vowel. Words such as 'an', 'anchored' or 'in' start with a vowel but end with a consonant, and 'village.' ends with a full stop, so they are not printed. Output:
Once a a awesome able
© examsnet.com
Advertisements
Go to Question: