【问题标题】:Searching for specific keywords in text Python在文本 Python 中搜索特定关键字
【发布时间】:2017-01-12 22:36:29
【问题描述】:

假设没有正则表达式,我想在一些包含 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”,请跳过它。

【问题讨论】:

  • 你目前的代码有什么问题
  • 您的线路应该包含"blue" "bunny" and "fluffy" 中的所有内容或其中任何一个?
  • 然后你需要调查那些 "few different things" 并找出问题出在哪里(或者如果你真的有问题) - 参见例如ericlippert.com/2014/03/05/how-to-debug-small-programs
  • @MoinuddinQuadri 是的,所有这些关键字都需要出现在该行中

标签: python regex string parsing keyword


【解决方案1】:

您可以使用all() 简化您的if 条件:

keywords = (keyword1, keyword2, keyword3)
if all(word in text for word in keywords) and badkeyword not in text:
    # Do something

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多