I have a script - generator that accepts a file name or file object and a list of search words as input. The generator searches through the lines of the file and returns only those lines (the whole line) where at least one of the search words is found.
from io import TextIOBase
from typing import TextIO
import mimetypes
def find_lines(object_or_filename: TextIO | str, search_words: list) -> str:
if isinstance(object_or_filename, str) and mimetypes.guess_type(object_or_filename)[0] == 'text/plain':
with open(object_or_filename, 'r', encoding="utf-8") as file:
for line in file:
lower_line = line.lower()
if any(word.lower() in lower_line.split() for word in search_words):
yield line.strip()
elif isinstance(object_or_filename, TextIOBase):
for line in object_or_filename:
lower_line = line.lower()
if any(word.lower() in lower_line.split() for word in search_words):
yield line.strip()
Is there a way to optimize this script and avoid code duplication of loop:
for line in file:
lower_line = line.lower()
if any(word.lower() in lower_line.split() for word in search_words):
yield line.strip()
I want that this loop was only used once but don't know how.