Question:medium

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 (!). Example:
If the content of the file STORY.TXT is:
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:
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?

Show Hint

Use split()} to separate text into sentences based on delimiters like .}, ?}, and !}. For handling multiple delimiters, additional splitting or regex can be used.
Updated On: Jan 13, 2026
Show Solution

Solution and Explanation

def showInLines():
    # Open the file STORY.TXT for reading.
    with open("STORY.TXT", "r") as file:
        content = file.read()  # Read the entire file content.
        sentences = content.split('. ')  # Split into sentences based on '. '.

        # Further process to correctly handle sentences ending with '?' or '!'.
        final_sentences = []
        for sentence in sentences:
            # Split by '? ' if present, otherwise by '! '.
            sub_sentences = sentence.split('? ') if '?' in sentence else sentence.split('! ')
            final_sentences.extend(sub_sentences)

        # Print each sentence on a new line.
        for sentence in final_sentences:
            print(sentence.strip())  # Remove leading/trailing whitespace.
    
Explanation: The file STORY.TXT is opened in read mode using with open(). The file's content is read into a string and then split into sentences using split('. '). For sentences that contain ? or !, additional splitting is performed to ensure accurate sentence separation. Each sentence is subsequently printed on a new line after removing any extraneous whitespace with strip().
Was this answer helpful?
0

Top Questions on Commands and Requests