Skip to content

Instantly share code, notes, and snippets.

@panchr
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panchr/0ecf09a9dcec75c55558 to your computer and use it in GitHub Desktop.
Save panchr/0ecf09a9dcec75c55558 to your computer and use it in GitHub Desktop.
Python string filtering
import re
FILTER_WORDS = ["spam", "morespam", "blahblah"] # and so forth
FILTER = re.compile("|".join(FILTER_WORDS))
def phrasePassesFilter(word):
'''Checks if the phrase passes the filter'''
return not bool(FILTER.match(word)) # if there are no matches, FILTER.match --> None, so it passes the filter
# otherwise, it's True so it contains a filtered word, so mark as spam
def isSpam(word):
'''Same as above, but just checks if spam and not if it passes the filter'''
return bool(FILTER.match(word))
print isSpam("my spam is so sneaky") # --> True
print phrasePassesFilter("my spam is so sneaky") # --> False
print isSpam("rushy") # --> False
print phrasePassesFilter("rushy") # --> True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment