如果匹配这些单词中的任何一个,则打印行

Print line if any of these words are matched

我有一个包含 1000 多行的文本文件,每行代表一篇关于我正在研究的主题的新闻文章。然而,此数据集中的数百 lines/articles 与该主题无关,我需要将其删除。

我已经使用 grep 删除了其中的许多 (grep -vwE "(wordA|wordB)" test8.txt > test9.txt),但我现在需要手动完成其余部分。

我有一个工作代码可以找到所有不包含特定单词的行,将这一行打印给我,并询问是否应该删除它。它运作良好,但我想包括其他几个词。例如。假设我的研究主题是肉食趋势。我希望编写一个脚本来打印不包含 'chicken' 或 'pork' 或 'beef' 的行,这样我就可以手动验证 lines/articles 是否与相关主题有关。

我知道我可以用 elif 做到这一点,但我想知道是否有更好更简单的方法?例如。我试过 if "chicken" or "beef" not in line: 但没用。

这是我的代码:

orgfile = 'text9.txt'
newfile = 'test10.txt'
newFile = open(newfile, 'wb')
with open("test9.txt") as f:
    for num, line in enumerate(f, 1):
        if "chicken" not in line:
            print "{} {}".format(line.split(',')[0], num)
            testVar = raw_input("1 = delete, enter = skip.")
            testVar = testVar.replace('', '0')
            testVar = int(testVar)
            if testVar == 10:
                print ''
                os.linesep
            else:
                f = open(newfile,'ab')
                f.write(line) 
                f.close()
        else:
            f = open(newfile,'ab')
            f.write(line) 
            f.close()

编辑:我尝试了 Pieter 对 this 问题的回答,但它在这里不起作用,大概是因为我没有使用整数。

您可以使用 any or all 和发电机。例如

>>> key_word={"chicken","beef"}
>>> test_texts=["the price of beef is too high", "the chicken farm now open","tomorrow there is a lunar eclipse","bla"]
>>> for title in test_texts:
    if any(key in title for key in key_words):
        print title


the price of beef is too high
the chicken farm now open
>>> 
>>> for title in test_texts:
    if not any(key in title for key in key_words):
        print title


tomorrow there is a lunar eclipse
bla
>>>