检查关键字是否存在于字符串中的任何容量中

2024-09-21 03:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

urgency = ["asap", "now", "quickly"]
test = 'the patientneeds help/asap'

if any(elem in test.split() for elem in urgency):
    print('Element Found')

当我运行此命令时,我希望能找到关键字“asap”,但不幸的是,这似乎只能进行精确匹配


Tags: theintestforifhelpanynow
3条回答

删除split()。但是inknownow将变成True

urgency = ["asap", "now", "quickly"]
test = 'the patientneeds help/asap'

if any(elem in test for elem in urgency):
    print('Element Found')

如果您想要特定的单词,并且想要避免像snowfallknow这样的触发器,例如,您可以尝试以下方法:

import re

urgency = ["asap", "now", "quickly"]
test = 'the patientneeds help/asap'

words = set(re.split(r"\W+", test))

if any(elem in words for elem in urgency):
    print('Element Found')

对于拆分“patientneeds”(没有字符分隔符连接的单词),似乎没有任何简单的解决方案,但这实际上为您提供了一个非常强大的机制

您应该使用正则表达式,并在每个搜索单词的开头和结尾添加一个单词边界\b的条件:

import re


def is_urgent(sentence):
    urgency = ["asap", "now", "quickly"]
    return any(re.search(r'\b' + urgent_word + r'\b', sentence) for urgent_word in urgency)

tests = ['the patient needs help/asap', 'he needs help asap', 'wait until snowfall']

for test in tests:
    if is_urgent(test):
        print('URGENT:', test)
    else:
        print('Not urgent:', test)
        

输出:

URGENT: the patient needs help/asap
URGENT: he needs help asap
Not urgent: wait until snowfall

相关问题 更多 >

    热门问题