CBSE Class 12 Computer Science Question 124 of 145

File Handling — Question 4

Back to all questions
4
Question

Question 4

Write a program to count the words "to" and "the" present in a text file "Poem.txt".

Answer

Let the file "Poem.txt" include the following sample text:

To be or not to be, that is the question.
The quick brown fox jumps over the lazy dog.
To infinity and beyond!
The sun sets in the west.
To be successful, one must work hard.
to_count = 0
the_count = 0

with open("Poem.txt", 'r') as file:
    for line in file:
        words = line.split()
        for word in words:
            if word.lower() == 'to':
                to_count += 1
            elif word.lower() == 'the':
                the_count += 1

print("count of 'to': ", to_count)
print("count of 'the': ", the_count)
Output
count of 'to': 4
count of 'the': 5