Skip to main content
 首页 » 编程设计

python之如何使用户输入不区分大小写

2025年05月04日18wuhuacong

我想创建一个函数来过滤我想打开的文件以及具体的月份和日期。这样,用户需要输入他们想要在特定月份或日期分析的城市(文件)。但是,我希望用户能够输入不区分大小写的内容。

例如,用户可以输入 'chicago'/'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) 

请您参考如下方法:

这样做的最佳方法就是获取所需的输入并将其转换为所需的大小写。

使用python的内置函数

variable.lower() 

或

variable.upper()