我想增强这个Python3代码(缩短),以便它也可以找到GreeTinGs这个词(没有匹配的情况)。我将使用的数据将是大写和小写混乱。我希望用户输入也可能包含大写和小写字母的单词(单词中的任何位置)。数据无法转换为全部较低或全部较高。 参考:它可以找到'HeLLo'而不是'GreeTinGs'。
目前,“casefold”命令适用于大多数用途;数据中间有大写字母。还有其他命令,如casefold或其他我可以使用的命令吗? 对于ref,还会有另一个输入,即区分大小写的搜索,这就是我需要两个选项的原因。
以下是代码,感谢所有帮助:
import random
greetings = ['hola', 'hello', 'GreeTinGs', 'hi', 'Hi', 'hey!','hey']
question = ['How are you?','How are you doing?']
responses = ['Okay',"I'm fine"]
while True:
userInput = input(">WHAT:").casefold()
if userInput in greetings:
greetingsrandom = random.choice(greetings)
print (greetingsrandom)
elif userInput in question:
responsesrandom = random.choice(responses)
print (responsesrandom)
else:
print("I did not understand what you said")
答案 0 :(得分:1)
对于不区分大小写,您可以将其全部设为大写
import random
greetings = ['hola', 'hello', 'GreeTinGs', 'hi', 'Hi', 'hey!','hey']
question = ['How are you?','How are you doing?']
responses = ['Okay',"I'm fine"]
while True:
userInput = input(">WHAT:").casefold()
if userInput.upper() in [x.upper() for x in greetings]:
greetingsrandom = random.choice(greetings)
print (greetingsrandom)
elif userInput in [x.upper() for x in question]:
responsesrandom = random.choice(responses)
print (responsesrandom)
else:
print("I did not understand what you said")