简体   繁体   中英

Finding uppercase lowercase words from an input, Python3.

I'd like to enhance this Python3 code (shortened) so that it can also find the word GreeTinGs (without matching the case). The data I will be using will be a mess of upper and lowercase. I'd like the user to type in words that also could contain upper and lowercase letters (anywhere in the word). The data cannot be converted to all lower or all upper. Ref: it can find 'HeLLo' but not 'GreeTinGs'.

Currently the "casefold" command fits most uses apart from where; the data has uppercase letters in the middle of the word. Is there another command like casefold or something else that I can use? For ref, there will also be another input, that will case sensitive search, this is why I need both options.

Here is the code and all help is appreciated:

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")

For case insensitivity you could make it all uppercase

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM