我正在编写一个函数,该函数在字符串中找到关键字并返回第一个匹配项(如果有)。
关键字是“ what”,“ when”,“ who”
示例:
是否可以将关键字列表与字符串输入进行比较并返回第一个匹配项?
我曾考虑过使用 re.search ,但是一次只需要一个字符串。 这是我到目前为止的内容:
question = input("Ask me a question: ")
keywords = ("what", "when", "who")
question = question.lower()
match = re.search(r'word:', question) # re.search seems to take only one string at a time
答案 0 :(得分:2)
将列表转换为\b(?:what|when|who)\b
形式的正则表达式,然后使用re.search()
。
question = input("Ask me a question: ").lower()
keywords = ("what", "when", "who")
kw_re = r'\b(?:' + '|'.join(map(re.escape, keywords)) + r')\b'
match = re.search(kw_re, question)
\b
匹配单词边界,因此只会匹配整个单词。
答案 1 :(得分:1)
测试包含在一组关键字中的单词是O(1)
,而测试O(n)
关键字列表是n
。
def find_match(sentence, keyword_set):
for word in sentence.split():
if word in keyword_set:
return word
keywords = {"what", "when", "who"}
question = "Who is John Connor".lower()
>>> find_match(question, keywords)
'who'
答案 2 :(得分:0)
将输入分割成多个单词,然后将每个单词与您的一组关键字进行比较;如果找到匹配项,则退出循环;如果要将其包装到函数中,则返回。
for word in question.split():
if word in keywords:
match = word
break
此外,请谨慎处理找不到匹配项的情况。
答案 3 :(得分:0)
这将在列表中找到第一个单词并为您提供位置:
question = input("Ask me a question: ")
keywords = ("what", "when", "who")
question = question.lower()
for keyword in keywords:
loc = question.find(keyword)
if loc == -1:
loc = "Not Found"
else:
print('{} was found at location: {} and is the first match found in the list of keywords'.format(keyword, loc))
break