python - 在 if 和 if not 语句中使用多个条件 (python)

标签 python python-3.x

我正在尝试从文本文件中读取文本、读取行并删除短行和包含特定字符串的行(例如“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/

相关文章:

python-3.x - 如何优化我的 Python 反向图像搜索以限制到特定域?

python - Python 中的 HLS Live Stream API 从磁盘提供文件

python "OverflowError: math range error"

python - 删除错误字符 "\xC2"python字符串

python - 将图表添加到 Flask Web 应用程序

python - 实习生如何处理不可变对象(immutable对象)?

python - 打印每个目录python的文件数

python - 尝试运行回归代码。收到有关 'linear_model' 的错误

python - 合并Python字典时保持插入顺序

python - Python 中调用 MySql 的超时