在 table 的特定列中搜索不匹配的项目

Searching a specific columns of a table for not matching items

with open("test.txt", "r") as test:
    reader = csv.reader(test, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
       for field in row:
            if field not in keywords:
                writer.writerow(row)
                break

这段代码似乎每一行都写了很多次。我猜它会查找每一列中的每个字段。如何指定单个列?

这是我现在正在使用的代码,它似乎遗漏了几行,其中关键字不存在于任何列中。

table = open("table.txt", "w")
with open("test.txt", "r") as test:
    reader = csv.reader(test, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

您可以使用 zip 获取列 then.You 可以在 all 函数中使用生成器表达式来检查所有元素是否满足条件 :

with open("test.txt", "r") as Spenn,open("test.txt", "r") as table:
    reader = zip(*csv.reader(Spenn, delimiter="\t"))
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

但是如果你只想写满足条件的行你可以使用下面的代码:

with open("test.txt", "r") as Spenn,open("test.txt", "r") as table:
    reader = csv.reader(Spenn, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)