Python-如何使用户输入不区分大小写? [英] Python - How to make user input not case sensitive?

查看:713
本文介绍了Python-如何使用户输入不区分大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Python and could really use some help on this. I want to create a function to filter which files I want to open and which months and day specifically. That way, the users need to input which city(files) they want to analyze on which particular month or day. However, I want the user to be able to input something that is not case sensitive. For example, the user can input 'chicago'/'CHICAGO"/"ChIcAgO" and the it still give you the right output and not the error handling message. Here is the code I use:

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)


推荐答案

做到这一点的最佳方法是仅接受所需的输入并将其转换为所需的大小写。

The best way to do so is just take the required input and convert it into the required case.

使用python的内置函数

Use the inbuilt functions of python

variable.lower()

variable.upper()

这篇关于Python-如何使用户输入不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆