176. Python Program to Find a Word in a File
MediumRead
Overview
Search a file line by line, the way a "Find" button does.
Problem Statement
Read a word on the first line. Then read a whole number n, then n lines of text, and write those lines into a file called text.txt, one per line.
Now read text.txt line by line and look for the word. For every line that contains it, print Found on line and the line number (the first line is 1). At the end, print Lines found: and how many lines contained it. If no line contains it, print only Not found.
- Capitals don't matter:
Catandcatare the same word. - Match whole words only:
funis not found infunny. Words are separated by spaces.
Your program runs in the browser, so the file lives only in this tab's memory. Create it with "w" before you read it.
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Input
The word, the number of lines, then the lines. Example:
cat
3
Sunny has a cat
Rocky has a dog
The Cat sleeps
Output
The output for that example:
Found on line 1
Found on line 3
Lines found: 2
The tests try 4 different inputs.