I created a function which replace word by special characters in string. It works well once I need to replace only one word. Now I need to have possibility to extend list of words from one to more (2, 3 4...).
Working code for one argument - word you can find below. What I need now is to have possibility to insert more than one word so it could be replaced in code by special signs.
def cenzura(text, word, sign="#"):
if word in text:
return text.replace(word, len(word)*sign)
else:
return text
cenzura("The day when I left", "day", sign="$")
CodePudding user response:
If you are happy masking all words in the list with the same symbol:
def cenzura_list(text, word_list, sign="#"):
for word in word_list:
text = cenzura(text, word, sign)
return text
cenzura_list("The day when I left", ["day", "I"], sign="$") # 'The $$$ when $ left'
To add: if you do need to mask different words with different symbols, you can use a dict
.
def cenzura_dict(text, mapping_dict):
for word in mapping_dict.keys():
text = cenzura(text, word, mapping_dict[word])
return text
cenzura_dict("The day when I left", {"day":"%", "I":"$"}) # 'The %%% when $ left'