Python 2.7 如果这些单词中的任何一个匹配,请打印行
我有一个1000多行的文本文件,每行代表一篇关于我正在研究的主题的新闻文章。然而,这个数据集中的几百行/文章与主题无关,我需要删除它们 我已经使用grep删除了其中的很多(Python 2.7 如果这些单词中的任何一个匹配,请打印行,python-2.7,if-statement,data-cleaning,Python 2.7,If Statement,Data Cleaning,我有一个1000多行的文本文件,每行代表一篇关于我正在研究的主题的新闻文章。然而,这个数据集中的几百行/文章与主题无关,我需要删除它们 我已经使用grep删除了其中的很多(grep-vwE“(wordA | wordB)“test8.txt>test9.txt),但是现在我需要手动完成其余的部分 我有一个工作代码,可以找到所有不包含某个单词的行,将这行打印给我,并询问是否应该删除它。它工作得很好,但我想包括其他几个词。比如说,我的研究主题是肉食趋势。我希望编写一个脚本,打印不包含“鸡肉”、“猪肉
grep-vwE“(wordA | wordB)“test8.txt>test9.txt
),但是现在我需要手动完成其余的部分
我有一个工作代码,可以找到所有不包含某个单词的行,将这行打印给我,并询问是否应该删除它。它工作得很好,但我想包括其他几个词。比如说,我的研究主题是肉食趋势。我希望编写一个脚本,打印不包含“鸡肉”、“猪肉”或“牛肉”的行,以便手动验证行/文章是否与相关主题相关
我知道我可以用elif做到这一点,但我想知道是否有更好更简单的方法?例如,我尝试了如果“鸡肉”或“牛肉”不符合要求:
但不起作用
以下是我的代码:
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对问题的回答,但在这里不起作用,可能是因为我没有处理整数 您可以使用或和生成器。比如说
>>> 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
>>>
“鸡”的可能复制品是真实的。这是真的。但我还是需要弄清楚!谢谢你的帮助!