1

the function is supposed to censor the words in the proprietary terms list:

proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
def  censored_list(text, List):
  for i in text:

    for word in List:
      if i == word:
        new_text = text.replace(i, "*" )
      return new_text
print(censored_list(email_two, proprietary_terms))  

but insted i get:

Traceback (most recent call last):
  File "script.py", line 19, in <module>
    print(censored_list(email_two, proprietary_terms))         
  File "script.py", line 18, in censored_list
    return new_text
UnboundLocalError: local variable 'new_text' referenced before assignment

another question, does the logic seems right?

EDIT:

Can anybody show me a working example code snippet of the code above?

ghghgh
  • 11
  • 3
  • 1
    You are declared `new_text ` in if statement and I think `if i == word:` not gonna execute so you are getting this error.Check your if condition – Omer Tekbiyik Jun 08 '20 at 13:50
  • See [this question](https://stackoverflow.com/q/15367760/4518341) for why you're getting the UnboundLocalError. For a solution, see [How to replace multiple substrings of a string?](https://stackoverflow.com/q/6116978/4518341) – wjandrea Jun 08 '20 at 14:00

2 Answers2

0

I think this is what you want:

import re
text = "She has a personality matrix in her sense of herself"
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
def  censored_list(text, List):
    print(text.lower())
    for word in List:
      print(word)
      if re.match('^(?=.*('+word+')).*$',text.lower()):
        print("Found:", word)
        text = text.lower().replace(word, "*" )
    return text
print(censored_list(text, proprietary_terms))



Prathamesh
  • 1,064
  • 1
  • 6
  • 16
0

i think this is what you want:

import re
text = "She has a personality matrix in her sense of herself"
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
def  censored_list(text, List):
    print(text.lower())
    for word in List:
      print(word)
      if re.match('^(?=.*('+word+')).*$',text.lower()):
        print("Found:", word)
        text = text.lower().replace(word, "*" )
    return text
print(censored_list(text, proprietary_terms))

But there are a few issues her why your code doesn't work:

  1. You need to declare new_text variable before using it. Otherwise the variable is not bound.

  2. You may need to use regular expressions, because what you are looking for can be quiet complex as long as you don't search for a single word.

user2853437
  • 750
  • 8
  • 27