Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove line if list of bad words are found

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. :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading