Home > Enterprise >  Remove line if list of bad words are found
Remove line if list of bad words are found

Time:09-14

Remove a line if an undesired word is found in the sentence. The bad words are cat and dog. Given a text file:

orange
cat is bad
dog is bad
water
egg

I would like it to look like:

orange
water
egg

Here is my code so far. I am not sure why this still returns a text file with the sentences that include the bad words. :

bad_words=[cat, dog]
with open('some.txt','r') as f:
   lines=f.readlines()

with open('some.txt','w') as f:
for i in lines:
   if  not any(bad_word in i for bad_word in bad_words):
      f.writelines(lines)

CodePudding user response:

change f.writelines(lines) to f.writelines(i)

  • Related