Python Program to Search for a Word in a File
Beginner · File handling
This program searches a text file for a word and prints every line the word appears on, with its line number, followed by how many times the word was found. The search ignores capital letters and punctuation, so "Python," and "python" both count.
Program
Line 1: Python is a popular language. Line 2: Many schools teach Python, and so do colleges. Line 4: I am learning python every day. "python" found 3 times
How it works
- The sample file has four lines, and "python" appears on lines 1, 2 and 4, twice with a capital P and once with a comma stuck to it.
enumerate(f, start=1)gives each line together with its line number, counting from 1.line.split()breaks the line into words, andw.strip(".,!?")removes punctuation from the ends of each word.- Comparing in lower case means "Python" and "python" both match, while a longer word such as "pythonic" does not.
totaladds up the matches from every line and decides the final message.
Another way to write it
Using in and count()
"popular" is in the file, 2 times
in and count() look for the letters anywhere in the text, so they are quick for a yes or no answer, but they are case sensitive and would also find "popular" inside "unpopular".
Try it yourself
Search for "popular", and then for "Ruby", to see both messages.
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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
- Count the Words "Me" and "My" in a Text File
- Count Words in a Text File
- Display Lines Starting with T in a Text File
- Count the Frequency of Words in a String
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- 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
All Python programs · CBSE class 12 practical file · Python exercises