Skip to content
Laviyx Learn

Try

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

  1. Read the file name and the words to search for (separated by spaces).
  2. 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.
  3. Open the file and read it line by line, keeping count of the line number.
  4. Split each line into words. Remove punctuation from the ends of each word and change it to lower case.
  5. If the word is one of the search words, add the line number to its list (once per line).
  6. Return the dictionary. If the file does not exist, print an error and stop.
  7. For each search word, print "found" with its line numbers if its list is not empty, otherwise print "not found".

Program

Python
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

Input file: notes.txt (Text)
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.
Output
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): 4

Recorded 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 line to check for a word. That looks for the letters anywhere, so is would be found inside list. 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 Python and python do not match.

  • Not removing punctuation, so language. with its full stop does not match language.

  • Not handling a wrong file name. Without try/except FileNotFoundError the 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 in chars from both ends of the string s. 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, in checks for a substring, so "is" in "list" is True. On a list, it checks for an equal element, so "is" in ["list"] is False.

Learn the concepts

All Python Programming Lab experiments →