Python Program to Count the Occurrence of Word “is” & “the” in Text File

Q. Write a program to count the occurrence of word “is” & “the” in text file in python.

file: text.txt
proram-to-count-total-number-of-words-in-text-file

Solution:

# print occurence of word "Is" & "The"
def read_data():
    f = open("text.txt", 'r')
    is_ = 0
    the_ = 0
    s = f.read()
    x = s.split()
    for i in x:
        if i == "is":
            is_ +=1
        elif i == "the":
            the_ +=1
        else:
            pass
    print("Occurence of Is is: "+ str(is_)+" and The is: "+str(the_))


read_data()

Output:

# Occurence of Is is: 0 and The is: 2

count-total-number-of-characters-in-a-text-file

Explanation: Here we have defined a function read_data(). Inside read_data() function we have also created a file object “f” and opened our text file in read mode ie. “r” mode.

In next step, we have initialized all the values to variable “s“. And used read() function to read our file word by word. The read() function return the output in string format.

Note: Here inside function, we have used split()  function which returns the list of words available in our text file. Here “s” is our file object.

split() method will separate each word from space and store them in list “x“.
After that we used for loop to iterate over each word present inside our list “x” and checked for the word “is” & “the” using if-elif-else statement. If word “is” found then we increment our variable “is_” by +1 and if word “the” found then we increment our variable “the_” value by +1. Hence at end, we’ll get the final result.

  1. Programming questions on Text Files

    1. WAP to define a method to read text document line by line.
    2. WAP to define a method in python to read lines from a text file starting with an alphabet F.
    3. WAP to define a method to count number of lines starting with an alphabet F.
    4. WAP to define a method which display only those lines starting with an alphabet A or F.
    5. WAP to define a method to display only those lines which are bigger than 50 characters.
    6. WAP to define a method to count total number of characters in our text file.
    7. WAP to define a method to count total numbers of word available in our text file.
    8. WAP to define a method which counts the occurrence of particular word in a text file.
    9. WAP to define a method which only print the words having more than 5 characters.

    Programming questions on Binary Files

    1. WAP to define a method which displays the records of student having marks between 50 & 70.
    2. WAP to define a method which displays only those student records who secured grade A.