How to Validate Text Against Forbidden Words in Python
Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.
Python code
23 linesdef validate_text(text, forbidden_words):
"""
Checks that text does not contain any forbidden words.
Returns (is_valid, offending_words) tuple.
"""
words = text.lower().split()
found = [word for word in words if word in forbidden_words]
return len(found) == 0, found
if __name__ == "__main__":
sample_texts = [
"The quick brown fox jumps over the lazy dog",
"This text contains bad words like spam and junk",
"Clean text without issues here",
]
forbidden = {"spam", "junk", "bad"}
for idx, text in enumerate(sample_texts, start=1):
is_valid, found = validate_text(text, forbidden)
status = "VALID" if is_valid else "INVALID"
details = f" (found: {found})" if found else ""
print(f"Text {idx}: {status}{details}")
Output
Text 1: VALID
Text 2: INVALID (found: ['bad', 'spam', 'junk'])
Text 3: VALID
How it works
This function normalizes the input text to lowercase and splits it into individual words using split(). A list comprehension checks each word against the forbidden set, which allows for O(1) lookups. The function returns a tuple where the first value is True if no forbidden words were found, and the second is the list of offending words (empty when valid). This pattern is simple and readable, making it easy to extend with additional checks like punctuation stripping.
Common mistakes
- Forgetting to convert the text to lowercase, causing case-sensitive mismatches.
- Using a list instead of a set for forbidden words, which slows down lookups on large lists.
- Not handling punctuation properly; 'spam,' would not match 'spam' without additional cleaning.
Variations
- Use `any(word in forbidden for word in words)` to only get a boolean result without collecting offending words.
- Strip punctuation with `re.findall(r'\b\w+\b', text.lower())` to ignore commas and periods.
Real-world use cases
- Moderating user-generated comments in a web app by filtering profanity or banned terms.
- Checking chatbot responses against a list of disallowed topics before sending them to users.
- Scanning code commit messages for sensitive keywords that should trigger a security review.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.