我正在尝试从文本文件中读取文本、读取行并删除短行和包含特定字符串的行(例如,“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 有关。知道如何调试吗?
答案 0 :(得分:1)
我已经编写了您代码的工作版本。您的问题是 or
。您应该使用 and
运算符,因为您希望仅当该行的长度大于 20 并且它不包含坏词时才将该行写入新文件。 >
代码:
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