""" poop.py by Peter Leow the pooper An entry to Coding Challenge: bad word filter https://www.codeproject.com/Answers/1157928/Coding-challenge-bad-word-filter#answer4 also published on http://pythonfiddle.com/coding-challenge-bad-word-filter/ """ import re def functionStartWithPoop(m): wordFound = m.group(0) if wordFound[:5].lower()=='poop*': wordRepl = wordFound[0] + '**' + wordFound[3] + wordFound[5:] else: #wordFound[:4].lower()=='poop': wordRepl = wordFound[0] + '**' + wordFound[3] + wordFound[4:] return wordRepl def functionEndWithPoop(m): wordFound = m.group(0) if wordFound[-5:].lower()=='*poop': wordRepl = wordFound[:-5] + wordFound[-4] + '**' + wordFound[-1] else: #wordFound[-4:].lower()=='poop': wordRepl = wordFound[:-4] + wordFound[-4] + '**' + wordFound[-1] return wordRepl def main(): originalSentence = ''' poop*ing is in front of make*poop. Whether poop* or *poop, there are just pOoP! A POOPHEAD cannot change but an exclaimed POOPHEAD! can.''' print('Before:') print(originalSentence) print() print('After:') # Without ! ending patternStartWithPoop=r'(?<!\S)poop\*?[\S]*' patternEndWithPoop=r'[\S]*\*?poop(?=[?!,.;]?$|[?!,.;]?\s+)' # with ! ending patternStartWithPoopEndWithExclamation = r'(?<!\S)poop\*?[\S]*!(?=\s|$)' patternEndWithPoopAndExclamation=r'[\S]*\*?poop!(?=[?!,.;]?$|[?!,.;]?\s+)' # Case sensitive filteredSentence = re.sub(patternStartWithPoop, functionStartWithPoop, originalSentence, flags=0) #print(filteredSentence) filteredSentence = re.sub(patternEndWithPoop, functionEndWithPoop, filteredSentence, flags=0) #print(filteredSentence) # Case ignorance filteredSentence = re.sub(patternStartWithPoopEndWithExclamation, functionStartWithPoop, filteredSentence, flags=re.IGNORECASE) #print(filteredSentence) filteredSentence = re.sub(patternEndWithPoopAndExclamation, functionEndWithPoop, filteredSentence, flags=re.IGNORECASE) print(filteredSentence) main()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question