[英]Finding uppercase lowercase words from an input, Python3.
我想增強此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")
對於不區分大小寫的情況,可以將其全部大寫
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.