在文本中搜索特定关键字 Python
Searching for specific keywords in text Python
假设没有正则表达式,我想在一些包含 3 个单词但不能有一个单词的文本中打印一行...我假设它看起来像这样:
在这个例子中,让 body 成为文本的集合
keyword1 = 'blue'
keyword2 = 'bunny'
keyword3 = 'fluffy'
badkeyword = 'rabies'
for link in links:
text = str(body)
if keyword1 in text and keyword2 in text and keyword3 in text and badkeyword not in text:
print("found line")
print(line)
我希望它打印带有 "blue" "bunny" 和 "fluffy" 的行,但如果该行恰好有 "rabies",请跳过它。
您可以使用 all()
简化您的 if
条件:
keywords = (keyword1, keyword2, keyword3)
if all(word in text for word in keywords) and badkeyword not in text:
# Do something
假设没有正则表达式,我想在一些包含 3 个单词但不能有一个单词的文本中打印一行...我假设它看起来像这样:
在这个例子中,让 body 成为文本的集合
keyword1 = 'blue'
keyword2 = 'bunny'
keyword3 = 'fluffy'
badkeyword = 'rabies'
for link in links:
text = str(body)
if keyword1 in text and keyword2 in text and keyword3 in text and badkeyword not in text:
print("found line")
print(line)
我希望它打印带有 "blue" "bunny" 和 "fluffy" 的行,但如果该行恰好有 "rabies",请跳过它。
您可以使用 all()
简化您的 if
条件:
keywords = (keyword1, keyword2, keyword3)
if all(word in text for word in keywords) and badkeyword not in text:
# Do something