I have written a script where I have a mocked data of couple of words in a list. The point is that I as a user will be able to input a text e.g. hello there world! and with this function I have written it should check if I have anything that matches and if it does it should print out that it matches else not.
import re
# mocked database
from collections import Iterable
get_keyword = [
"shorts",
"red banan",
"hello world",
"t-shorts",
"boxers",
]
find_words = re.compile(r'\w+').findall
words = {word.lower() for word in find_words('hello test worldd')}
single_negative: set[str] = set()
multi_negative: list[set[str]] = []
for db_keyword in get_keyword:
if " " in db_keyword:
multi_negative.append(set(db_keyword.split()))
else:
single_negative.add(db_keyword)
def matches(single: set[str], multi: Iterable[set[str]]) -> bool:
return (not words.isdisjoint(single)) or any(multi_word <= words for multi_word in multi)
if matches(single_negative, tuple(multi_negative)):
# Did find any match
print('Match found!')
else:
# Did not find matches
print('Match NOT found!')
There is some scenarios to keep in mind is that e.g.
- If we have "hello world" in our list and the word we want to match is "hello there world" -> that should be print out as match as we can find both word hello and world inside "hello there world"
- If we have "hello world" in our list and we have the world "hello there" -> that should print out not matched as we need to find both word "hello" and "world" inside "hello there"
- If we have "hello" in our list and we have the world "Master, hello there!" -> that should be print out match found as we just want to see if the word hello is inside "Master, hello there!"
Hope anyone have some spare time to see if I could improve anything :D