3

I'm trying to read a text from a text file, read lines, and delete short lines and lines that contain specific string (for example, 'bad' and 'naughty'). I can't seem to make this happen with this code:

bad_words = ['bad', 'naughty']

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words) or len(line) > 20:
            newfile.write(line)

I suspect that the problem has to do with using if and if not. Any idea how to debug this?

6
  • Do you really have a :: there? That's going to be a SyntaxError... Commented Feb 24, 2021 at 18:07
  • Fixing your syntax error(s) would be a good start. Commented Feb 24, 2021 at 18:07
  • thanks. fixed the syntax error. now I would love to know hoe to make the code do what I want (: Commented Feb 24, 2021 at 18:09
  • You also say bad "words" but your current code is looking for substrings... but the main thing is... you don't want or/the not here... have a think about your boolean logic :) Commented Feb 24, 2021 at 18:10
  • 2
    @ScottHunter think you've given away what I was trying to hint there :p (OP: once that clicks - I'd also move the length check first as that's a much faster check to make before looking at the content of the string - good luck!) Commented Feb 24, 2021 at 18:20

1 Answer 1

2

I have written a working version of your code. Your problem was the or. You should use the and operator because you want to write the line to the new file only if the lenght of the line is grater than 20 AND it doesn't contains bad word.

Code:

bad_words = ["bad", "naughty"]

with open("oldfile.txt") as oldfile, open("newfile.txt", "w") as newfile:
    for line in oldfile:
        if len(line) > 20 and not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

Test:

oldfile.txt content:

Short line
This is a very long lineeeeeeeeeeeeeee
This is a bad line
This is a naughty line
This is also a very good line

Run the script:

>>> python3 test.py

newfile.txt content:

This is a very long lineeeeeeeeeeeeeee
This is also a very good line
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.