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.
Use the inbuilt functions of python
variable.lower()
or
variable.upper()