3

I'm using a simple system to check if some banned words are currently in a string but I'd like to improve it to display the word in question so I added the line

print ("BANNED WORD DETECTED : ", word)

But I get the error

"NameError: name 'word' is not defined"

If think that the problem is that my system is just checking if any of the words is in the list without "storing it" somewhere, maybe I am misunderstanding the python list system, any advice of what I should modify ?

# -*- coding: utf-8 -*-

bannedWords = ['word1','word2','check']
mystring = "the string i'd like to check"

if any(word in mystring for word in bannedWords):
    print ("BANNED WORD DETECTED : ", word)
else :
    print (mystring)
RoiYeti
  • 35
  • 2
  • 7
  • Take a look here : https://stackoverflow.com/questions/16505456/how-exactly-does-the-python-any-function-work – Daneel Aug 15 '17 at 08:58

3 Answers3

4

any() isn't suitable for this, use a generator expression with next() instead or a list comprehension:

banned_word = next((word for word in mystring.split() if word in bannedWords), None)
if banned_word is not None:
   print("BANNED WORD DETECTED : ", word)

Or for multiple words:

banned_words = [word for word in mystring.split() if word in bannedWords]
if banned_words:
    print("BANNED WORD DETECTED : ", ','.join(banned_words))

For improved O(1) membership testing, make bannedWords a set rather than a list

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • thank you for the help, this works perfectly. I just want to point out something that another user said before deleting his post, you can also add ".lower()" before ".split()" to check the list of words without considering the case. – RoiYeti Aug 15 '17 at 09:30
  • 1
    @RoiYeti Sure, you can use `mystring.lower().split()` for a case insensitive search (assuming all the banned words are also lower case). Or use `str.casefold()`. Don't delete the question, this may be a useful question for others in the future too, that's how SO works! – Chris_Rands Aug 15 '17 at 09:45
3

Don't use any here. A generator isn't the right tool either. You actually want a list comprehension to collect all the matching words.

matching = [word for word in bannedWords if word in mystring]
if matching:
    print ("BANNED WORD(S) DETECTED : ", ','.join(matching))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

you could do that very easily :-

Just take a referance variable to check if it found anything within the loop.

detected = False ;
for word in bannedWords:
     if word in mystring :
          detected = True ;
          print("Detected Banned word " ,word) ;

if not detected:
     print(mystring ) ;

If you want a more pythonic way :-

print("Banned words are {}".format([word for word in bannedWords if word in mystring]) if len([word for word in bannedWords if word in mystring]) else mystring) ;
Natesh bhat
  • 12,274
  • 10
  • 84
  • 125