Python Lab · Experiment 32
Check whether given words are present in a file
PythonWeek 7JNTUH R22 · CS206ES
Aim
To write a Python program that opens a given text file and uses a function to check whether each of the given words is present in it, displaying each word that is found with the line numbers where it occurs.
Algorithm
- Read the file name and the words to search for (separated by spaces).
- In the function
find_words(file_name, words), make a dictionary that maps each search word, in lower case, to an empty list of line numbers. - Open the file and read it line by line, keeping count of the line number.
- Split each line into words. Remove punctuation from the ends of each word and change it to lower case.
- If the word is one of the search words, add the line number to its list (once per line).
- Return the dictionary. If the file does not exist, print an error and stop.
- For each search word, print "found" with its line numbers if its list is not empty, otherwise print "not found".
Program
import string
def find_words(file_name, words):
found = {word.lower(): [] for word in words}
with open(file_name, "r") as f:
for line_no, line in enumerate(f, start=1):
for token in line.split():
token = token.strip(string.punctuation).lower()
if token in found and line_no not in found[token]:
found[token].append(line_no)
return found
file_name = input("Enter file name: ")
words = input("Enter words to search: ").split()
try:
result = find_words(file_name, words)
except FileNotFoundError:
print("Cannot open file", file_name)
else:
for word, lines in result.items():
if lines:
print(f"'{word}' found on line(s):", ", ".join(str(n) for n in lines))
else:
print(f"'{word}' not found")Output
Python is a popular language.
A list in Python can hold values of any type.
Lists, tuples and dictionaries are collections.
A for loop goes through a list one item at a time.Enter file name: notes.txt
Enter words to search: python list Java loop
'python' found on line(s): 1, 2
'list' found on line(s): 2, 4
'java' not found
'loop' found on line(s): 4Recorded by running this exact program. Typed input appears after each prompt.
How it works
The search matches whole words and ignores upper and lower case. So python is found as Python, but list is not counted inside Lists on line 3, because lists is a different word. token.strip(string.punctuation) removes marks such as . and , from both ends of a word, so language. is compared as language.
string.punctuation is the string of all ASCII punctuation characters: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.
enumerate(f, start=1) gives each line together with its line number, counting from 1.
To check for a word as plain text anywhere in the file (so that list would also be found inside Lists), you could instead test word in text.lower() on the whole file text.
Common mistakes
Using
word in lineto check for a word. That looks for the letters anywhere, soiswould be found insidelist. Split the line into words and compare whole words.Forgetting to change both the file's words and the search words to the same case. Then
Pythonandpythondo not match.Not removing punctuation, so
language.with its full stop does not matchlanguage.Not handling a wrong file name. Without
try/except FileNotFoundErrorthe program stops with a traceback.
Viva questions
Try to answer each one aloud before you open it.
What does enumerate() do?
It goes through a sequence and gives each item together with its position, as pairs (index, item).
enumerate(f, start=1)numbers the lines of a file from 1.What does the strip() method do when it is given an argument?
s.strip(chars)removes any of the characters incharsfrom both ends of the strings. Without an argument it removes spaces and other whitespace.Why is a dictionary used to store the results?
Each search word is a key and its list of line numbers is the value, so looking up a word is fast and the results stay together with each word.
How do you read a file line by line in Python?
Loop over the file object:
for line in f:. Each line comes with its newline character at the end.What is the difference between the in operator on a string and on a list of words?
On a string,
inchecks for a substring, so"is" in "list"isTrue. On a list, it checks for an equal element, so"is" in ["list"]isFalse.
Learn the concepts
- Python File Handling: Read, Write and Append Files (with open and pathlib)
- Python Strings: Indexing, Slicing, Methods and f-strings
- Python Dictionaries: Keys, Values, Methods and Real Examples
- Python Functions: def, Parameters and return Explained Simply
- Python Exceptions: try, except, else, finally and raise