CBSE · 083Class XII · 2024Section C3 marks
Question 28
2 April 2024 · Computer Science (083)
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 :
text
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 :
text
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?Answer
python
def showInLines():
with open("STORY.TXT", 'r') as F:
content = F.read()
sentence = ""
for ch in content:
sentence += ch
if ch in "." + "?" + "!":
print(sentence)
sentence = ""
if sentence:
print(sentence)Explanation
Builds up a sentence character by character; whenever a terminator (., ?, !) is hit, the accumulated sentence is printed on its own line and the buffer resets.