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


You can understand by Watching video :-



Answer :-

to_no = 0
the_no = 0

file = open("Poem.txt", "r")
lst = file.readlines()

for i in lst :
    word = i.split()
    for j in word :
        if j == "to" or j == "To" :
            to_no  += 1
        elif j == "the" or j == "The" :
            the_no  += 1

print("Number 'to' : " , to_no)
print("Number 'the' : " , the_no)

file.close()

Poem.txt Contains :-

This is the Path Walla Website.
We are going to do some Python code

Like a joy on the heart of a sorrow,
The sunset hangs on a cloud;
A golden storm of glittering sheaves,
Of fair and frail and fluttering leaves,
The wild wind blows in a cloud.

Hark to a voice that is calling
To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have gone,
And why should I stay behind?

Output :-

Number 'to' :  3
Number 'the' :  7

>>>





10 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

  1. What is readline and split() work in these program

    ReplyDelete
  2. I dont understand properly in these function's work

    ReplyDelete
  3. Can we use read() in it and then use or in between conditions and taking output as combination of both the and to

    ReplyDelete

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post