【问题标题】:Finding uppercase lowercase words from an input, Python3.从输入中查找大写小写单词,Python3。
【发布时间】:2014-12-14 01:01:02
【问题描述】:

我想增强这个 Python3 代码(缩短),以便它也可以找到单词 GreeTinGs(不匹配大小写)。我将使用的数据将是大写和小写的混乱。我希望用户输入也可以包含大写和小写字母的单词(单词中的任何位置)。数据不能转换为全低或全高。 参考:它可以找到“HeLLo”,但不能找到“GreeTings”。

目前,“casefold”命令适用于除 where 之外的大多数用途;数据在单词中间有大写字母。是否有其他命令,例如 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")

【问题讨论】:

  • 为什么输入不能转换为all-lower?
  • 为什么你可以使用str.casefold(),而不是lower()upper()?这是一个完全任意的限制,如果有这样的限制,那么casefold() 可能是不允许的either
  • 因为它将包含编程代码,一个框架的帮助文件。如果他们在单词中途输入了错误的大小写,我希望搜索能够找到它。但是,我不希望系统在显示时显示错误的大小写。

标签: python uppercase lowercase


【解决方案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")

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多