gpt4 book ai didi

python - 按特定顺序测试多个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:10 25 4
gpt4 key购买 nike

有没有办法按特定顺序测试多个字符串?像这样:

if str.find(["who", "are", "you"], "who the heck are you") != -1:
Print("I AM JOE")

最佳答案

逐字测试,检查每个关键字是否包含在前一个关键字之后。

def find_in_order(text, words):
tokens = text.split()
start = 0
for word in words:
try:
start = tokens.index(word, start) + 1
except:
return False
return True

测试:

>>> find_in_order("who the hell are you", ["who", "are", "you"])
True
>>> find_in_order("who the hell is you", ["who", "are", "you"])
False
>>> find_in_order("you who the hell are you", ["who", "are", "you"])
True
>>> find_in_order("who bare bayou", ["who", "are", "you"])
False
>>> find_in_order("who are you", ["who", "are", "are", "you"])
False

或者使用不在空格处拆分的变体,因此 who bare byou 将通过:

def find_in_order(text, words):
start = 0
for word in words:
try:
start = text.index(word, start) + len(word)
except:
return False
return True

关于python - 按特定顺序测试多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com