CBSE · 083Class XII · 2023Section C3 marks

Question 27(1)

30 March 2023 · Computer Science (083)

Write the definition of a Python function named LongLines() which reads the contents of a text file named 'LINES.TXT' and displays those lines from the file which have at least 10 words in it.

For example, if the content of 'LINES.TXT' is :

text
Once upon a time, there was a woodcutter
He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.

Then the function should display :

text
He lived in a little house in a beautiful, green wood.
He saw a little girl skipping through the woods, whistling happily.

Answer

python
def LongLines():
    with open('LINES.TXT', 'r') as myfile:
        for line in myfile:
            if len(line.split()) >= 10:
                print(line)

Explanation

Opens the file, iterates line by line, splits each line on whitespace to get a word list, and prints lines whose word count is at least 10.