It is necessary to enter an array of values in the pattern from re.sub (pattern, repl, string) I don’t know how this can be implemented I tried like this:
from re import sub
def filter_words (phrase):
for word in "bad | mean | ugly | horrible | hideous" .split ("|"):
if word in phrase.lower ():
return sub (word, "awesome", phrase)
An example of how the code works: we enter the line “You said he was a bad dog.” — & gt; “You said he was a awesome dog.”
And a similar replacement occurs with all words from this line “bad | mean | ugly | horrible | hideous” .
Answer 1, authority 100%
Regular expressions to search for whole words must be wrapped in \ b
.
The PATTERN_TEXT
will contain the following pattern:
\ bbad \ b | \ bmean \ b | \ bugly \ b | \ bhorrible \ b | \ bhideous \ b
Example:
import re
WORDS = "bad", "mean", "ugly", "horrible", "hideous"
PATTERN_TEXT = '|' .join (fr "\ b {word} \ b" for word in WORDS)
PATTERN = re.compile (PATTERN_TEXT, flags = re.IGNORECASE)
def filter_words (phrase):
return PATTERN.sub ("awesome", phrase)
print (filter_words ("You said he was a bad dog."))
# You said he was a awesome dog.
print (filter_words ("You said he was a badass dog."))
# You said he was a badass dog.
If you need it without a complete match by word, then you need to remove \ b
:
import re
WORDS = "bad", "mean", "ugly", "horrible", "hideous"
PATTERN = re.compile ('|' .join (WORDS), flags = re.IGNORECASE)
def filter_words (phrase):
return PATTERN.sub ("awesome", phrase)
print (filter_words ("You said he was a bad dog."))
# You said he was a awesome dog.
print (filter_words ("Go on Tony you, horribleish person!"))
# Go on Tony you, awesomeish person!