我正在尝试从文本文件中读取文本、读取行并删除短行和包含特定字符串的行(例如“bad”和“naughty”)。 我似乎无法使用此代码实现此目的:
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)
我怀疑问题与使用 if 和 if not 有关。知道如何调试吗?
最佳答案
我已经编写了您的代码的工作版本。你的问题是或
。您应该使用 and
运算符,因为只有当该行的长度大于 20 AND 它不包含坏词时,您才想将该行写入新文件.
代码:
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)
测试:
oldfile.txt 内容:
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
运行脚本:
>>> python3 test.py
newfile.txt 内容:
This is a very long lineeeeeeeeeeeeeee
This is also a very good line
关于python - 在 if 和 if not 语句中使用多个条件 (python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66356438/