Home > Enterprise >  Censoring a txt file with python
Censoring a txt file with python

Time:10-20

Hi I could really use some help on a python project that I'm working on. Basically I have a list of banned words and I must go through a .txt file and search for these specific words and change them from their original form to a ***.

text_file = open('filename.txt','r')
text_file_read = text_file.readlines()
banned_words = ['is','activity', 'one']
words = []
i = 0
while i < len(text_file_read):
    words.append(text_file_read[i].strip().lower().split())
    i  = 1
i = 0
while i < len(words):
    if words[i] in banned_words:
        words[i] = '*'*len(words[i])
    i  = 1

i = 0
text_file_write = open('filename.txt', 'w')
while i < len(text_file_read):
    print(' '.join(words[i]), file = text_file_write)
    i  = 1

The expected output would be:

This **
   ********
***?

However its:

This is 
activity 
one?

Any help is greatly appreciated! I'm also trying not to use external libraries as well

CodePudding user response:

I cannot solve this for you (haven't touched python in a while), but the best debugging tip I can offer is: print everything. Take the first loop, print every iteration, or print what "words" is afterwards. It will give you an insight on what's going wrong, and once you know what is working in an unexpected way, you can search how you can fix it.

Also, if you're just starting, avoid concatenating methods. It ends up a bit unreadable, and you can't see what each method is doing. In my opinion at least, it's better to have 30 lines of readable and easy-to-understand code, than 5 that take some brain power to understand.

Good luck!

CodePudding user response:

A simpler way if you just need to print it

banned_words = ['is','activity', 'one']
output = ""
f = open('filename.txt','r')
for line in f:
    for word in line.rsplit():
        if not word in banned_words:
            output  = word   " "
        else:
            output  = "*"*len(word)   " "
    output  = "\n"

print(output)
  • Related