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
line.split()turns each line of the file into a list of words.word.strip(".,?!")removes punctuation from both ends of a word, so "Me?" and "diary." can be compared cleanly..lower()makes the check ignore case, so "My", "my" and "MY" all count.- Comparing whole words with
==keeps "Myra" out of the count, which a check like"my" in linewould 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.
Related programs
- Count Words in a Text File
- Display Lines Starting with T in a Text File
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Read a Text File and Separate Words with #
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Read a File Line by Line
All Python programs · CBSE class 12 practical file · Python exercises