- I am looking to understand what it takes to replace certain words from my .TXT file.
- Those certain words would be strings in a censored_words list.
I was successful with a single-word replacement:
email = open('email.txt', 'r').read()
def single_string_replace(email):
return email.replace('word1', 'REDACTED')
But I could not get a list of words to work "flawlessly". This is my attempt:
email = open('email.txt', 'r').read()
banned_words = ['word1', 'phrase one']
def list_replace(email):
list_place = 0
while list_place < len(banned_words):
for word in banned_words:
email = email.replace(word, 'REDACTED')
list_place += 1
return email
I am optimally looking to keep the .TXT files unchanged, and only seeing the changes by a print() statement such as
print(list_replace(email))
The issue that I am having is:
- Let's say I ban a word such as dog, and also ban the word hotdog. If 'dog' is first up in the list, then when 'hotdog' is being searched for ban, it doesn't find any.
- This creates 'hotREDACTED' instead of 'REDACTED'.
- Vice versa as well. If I want the word dog banned, but hotdog is okay, how can I make sure both of these above cases work without kinks?
As always has been, is, and shall be: all suggestions are welcome!
Thank you