This thread is a continue version of Find match words based on a list of words where I now have added Good word dictionary. What I am trying achieve here is that I want to check if a user has a given sentence of e.g. "hello world" - Then we want to see if the sentence contains good word and NOT any bad word. If that's if statement is true, then we should print out True otherwise print out False.

This is what I have done:

import re
from dataclasses import dataclass
from typing import AbstractSet, Iterable

from lib.database import Raffle, Keyword

WORD_BREAKER = re.compile(r"[-'\w]+")

class Words:
    Bad words database.
    combos: AbstractSet[AbstractSet[str]]

    def new(cls, words: Iterable[str]) -> "Words":
        Create a new Words instance.

        :param words: Iterable[str] - The words collection
        :return: BadWords - The words instance

        return cls(frozenset(
            for phrase in words

    def matches(self, sentence: str) -> bool:
        Check if the sentence contains any bad words.

        :param sentence: str - The sentence to check
        :return: bool - True if the sentence contains any bad words

        words = frozenset(WORD_BREAKER.findall(sentence.casefold()))
        return any(combo <= words for combo in self.combos)

BadWords = Words
GoodWords = Words

def get_filter_bad_word_db() -> BadWords:
    Get the bad words database.

    :return: BadWords - The bad words database

    return BadWords.new(Keyword.get_bad_keyword())

def get_filter_good_word_db() -> GoodWords:
    Get the good words database.

    :return: GoodWords - The good words database

    return GoodWords.new(Keyword.get_good_keyword())

given_sentence = "hello world"

if get_filter_good_word_db().matches(given_sentence) and not get_filter_bad_word_db().matches(given_sentence):
    """TODO: Do something"""


A small concern (or thinking what I could perhaps improve) could be the given variable "sentence" for both get_filter_good_word_db.matches and get_filter_bad_word_db.matches e.g.

get_filter_good_word_db().matches(given_sentence) and not get_filter_bad_word_db().matches(given_sentence)

but not sure and hopefully I could get a review on this :) Much appreciated!

  • 1
    \$\begingroup\$ Ahoy! I adjusted the formatting in revision 2. Please ensure it is formatted as the code should be, otherwise please click the edit link to correct it. \$\endgroup\$ Sep 8 at 21:02
  • \$\begingroup\$ @SᴀᴍOnᴇᴌᴀ Appreciate that! :) \$\endgroup\$ Sep 8 at 21:29


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.