Test Index

File Handling in Python Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 19 of 37
Marks: +1, -0
(A) Write a user defined function in Python named showInLines() which reads contents of a text file named STORY.TXT and displays every sentence in a separate line.
Assume that a sentence ends with a full stop (.), a question mark (?), or an exclamation mark (!).
For example, if the content of file STORY.TXT is as follows :
Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were right! So, what else did our parents tell?
Then the function should display the file's content as follows :
Our parents told us that we must eat vegetables to be healthy.
And it turns out, our parents were right!
So, what else did our parents tell?
OR
(B) Write a function, c_words() in Python that separately counts and displays the number of uppercase and lowercase alphabets in a text file, Words.txt.
[CBSE 2024 Set 4]
Solution:  
(A)
def showInLines():
F = open("STORY.TXT", "r")
data = F.read()
F.close()
sentence = ""
for ch in data:
if ch == "\n": # a line break inside a sentence
ch = " "
sentence = sentence + ch
if ch in ".?!": # end of a sentence
print(sentence.strip())
sentence = ""
if sentence.strip() != "": # text after the last full stop, if any
print(sentence.strip())
Explanation: The whole file is read into a string and checked character by character. Characters are collected into sentence; when a full stop, question mark or exclamation mark is reached, the sentence is printed on its own line (strip() removes the space left before it) and a new sentence begins.
OR (B)
def c_words():
F = open("Words.txt", "r")
data = F.read()
F.close()
upper = 0
lower = 0
for ch in data:
if ch.isupper():
upper = upper + 1
elif ch.islower():
lower = lower + 1
print("Number of uppercase alphabets:", upper)
print("Number of lowercase alphabets:", lower)
c_words()
Key point: isupper() and islower() are True only for letters, so digits, spaces and punctuation are not counted.
© examsnet.com
Advertisements
Go to Question: