Editor

Python Program to Count the Words "Me" and "My" in a Text File

Beginner · File handling · CBSE class 12 practical list

This program reads a text file and counts how many times the words "Me" and "My" appear in it, in any mix of capital and small letters. It matches whole words only, so a name like Myra is not counted as "My". It is a common CBSE class 12 file handling question.

Program

count_me_my_in_file.py
# Make a sample file to work on (in your practical file, this file already exists)
with open("diary.txt", "w") as f:
f.write("My name is Riya and this is my diary.\n")
f.write("Myra came home with me today.\n")
f.write("She gave me my book, then left.\n")
f.write("Me? I just smiled at my mum.\n")
me_count = 0
my_count = 0
with open("diary.txt", "r") as f:
for line in f:
for word in line.split():
word = word.strip(".,?!").lower() # "Me?" becomes "me"
if word == "me":
me_count += 1
elif word == "my":
my_count += 1
print("Me appears", me_count, "times")
print("My appears", my_count, "times")
print("Me and My together:", me_count + my_count)
Output
Me appears 3 times
My appears 4 times
Me and My together: 7

How it works

  1. line.split() turns each line of the file into a list of words.
  2. word.strip(".,?!") removes punctuation from both ends of a word, so "Me?" and "diary." can be compared cleanly.
  3. .lower() makes the check ignore case, so "My", "my" and "MY" all count.
  4. Comparing whole words with == keeps "Myra" out of the count, which a check like "my" in line would get wrong.

Another way to write it

As a function, the way exam questions ask

As a function, the way exam questions ask
# Make a sample file to work on (in your practical file, this file already exists)
with open("diary.txt", "w") as f:
f.write("My dog follows me everywhere.\nMe and my dog love the park.\n")
def count_me_my(filename):
count = 0
with open(filename, "r") as f:
for word in f.read().split():
if word.strip(".,?!").lower() in ["me", "my"]:
count += 1
return count
print("Me and My appear", count_me_my("diary.txt"), "times")
Output
Me and My appear 4 times

Board questions usually say "write a function". This one returns a single total for both words, and f.read().split() takes every word of the file at once.

Try it yourself

Change the program to count the words "the" and "is" instead.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises