Python - 如何使用户输入不区分大小写?

时间:2018-05-05 18:50:59

标签: python user-input case-insensitive

我是Python新手,可以真正使用一些帮助。我想创建一个函数来过滤我想要打开的文件以及特定的月份和日期。这样,用户需要输入他们想要在哪个特定月份或日期分析哪个城市(文件)。但是,我希望用户能够输入不区分大小写的内容。 例如,用户可以输入芝加哥' CHICAGO" /" ChIcAgO"它仍然给你正确的输出,而不是错误处理消息。这是我使用的代码:

def get_filters ():

    city_options = ['Chicago','New York City','Washington']
    month_options = ['January','February','March','April','May','June','All']
    day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','All']
    while True:
        try:
            city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'))
            month = month_options.index(input('\nInsert month to filter by or "All" to apply no month filter! (January, February, etc.)\n'))
            day = day_options.index(input('\nInsert day of the week to filter by or "All" to apply no day filter! (Monday, Tuesday, etc.)\n'))
            return city_options[city].lower(), month_options[month].lower(), day_options[day].lower()
        except ValueError:
            print ("Your previous choice is not available. Please try again")

def load_data (city,month,day):

    #load data file into DataFrame
    df = pd.read_csv(CITY_DATA[city].lower())

    #convert start time column (string) to datetime
    df['Start Time']=pd.to_datetime(df['Start Time'])

    #create new column to extract month and day of the week from start time
    df['Month'] = df['Start Time'].dt.month
    df['Day_of_Week'] = df['Start Time'].dt.weekday_name

    #filter by month if applicable
    if month.lower()!= 'All':
        #use the index of the month list to get corresponding into
        months = ['January', 'February', 'March', 'April', 'May', 'June']
        month = months.index(month) + 1
        #filter by month to create new dataframes
        df = df[df['Month'] == month]

    if day.lower()!= 'All':
        #filter by day_of_week to create new DataFrames
        df =df[df['Day_of_Week'] == day]

    return(df)

3 个答案:

答案 0 :(得分:2)

最好的方法是获取所需的输入并将其转换为所需的大小写。

使用python的内置函数

variable.lower()

variable.upper()

答案 1 :(得分:1)

我也是新手,但我认为你应该看一下字符串函数。假设您使用python 3,因为您使用输入并且没有得到ValueError,您可以在输入的括号之后添加.lover()。title()

示例:

city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n').lower().title())

如果您输入cHIcaGO,它应该可以立即转换为芝加哥。

希望它有所帮助!

编辑:(在纠正了lower()函数的拼写错误后,在webbrowser,pycharm和Python本身上尝试了它。对我来说工作正常(我使用的是python 2.7所以我将所有输入更正为raw_input,如果你使用的是python 3你不必改变它们。)。)

答案 2 :(得分:1)

您应该使用str.casefold来消除区分大小写。根据{{​​3}},这比str.lower更严格:

  

<强> str.casefold()

     

返回字符串的已装入案例的副本。 可以使用案例折叠字符串   无情匹配。

     

Casefolding类似于小写,但更具攻击性,因为它   旨在删除字符串中的所有大小写区别。例如,   德语小写字母'ß'相当于“ss”。因为它是   已经小写,lower()对'ß'没有任何作用; casefold()   将其转换为“ss”。

例如:

x = 'ßHello'

print(x.casefold())

sshello