You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现用户输入不区分大小写?含城市文件筛选函数开发需求

实现不区分大小写的筛选函数方案

我来帮你搞定这个get_filters()函数,刚好能满足你要的不区分大小写输入,还有月份、日期筛选的需求~下面是完整的实现思路和代码:

核心思路

  1. 统一输入格式:把用户输入的字符串转成小写(或大写),再和预设的合法选项对比,彻底解决大小写不匹配的问题
  2. 输入验证循环:用while True循环确保用户输入的内容在合法范围内,直到输入正确才退出
  3. 预设合法选项:提前定义好可选择的城市、月份、日期列表,避免无效输入

完整代码实现

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze (lowercase)
        (str) month - name of the month to filter by, or "all" (lowercase)
        (str) day - name of the day of week to filter by, or "all" (lowercase)
    """
    print('Hello! Let\'s explore some US bikeshare data!')
    
    # 预设合法选项,统一用小写存储
    valid_cities = ['chicago', 'new york city', 'washington']
    valid_months = ['all', 'january', 'february', 'march', 'april', 'may', 'june']
    valid_days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']

    # 获取并验证城市输入
    while True:
        city_input = input("\nWhich city would you like to analyze? Chicago, New York City, or Washington? ").strip()
        city = city_input.lower()
        if city in valid_cities:
            break
        else:
            print(f"Oops, '{city_input}' isn't a valid option. Please choose from Chicago, New York City, or Washington.")

    # 获取并验证月份输入
    while True:
        month_input = input("\nWhich month would you like to filter by? Enter 'all' for no filter, or a month name (January-June): ").strip()
        month = month_input.lower()
        if month in valid_months:
            break
        else:
            print(f"Sorry, '{month_input}' isn't valid. Enter 'all' or a month from January to June.")

    # 获取并验证日期输入
    while True:
        day_input = input("\nWhich day of the week? Enter 'all' for no filter, or a day name (Monday-Sunday): ").strip()
        day = day_input.lower()
        if day in valid_days:
            break
        else:
            print(f"Invalid input: '{day_input}'. Please enter 'all' or a day from Monday to Sunday.")

    print('-'*40)
    return city, month, day

关键细节解释

  • .strip().lower()处理:strip()去掉输入前后的空格(避免用户误输入空格导致匹配失败),lower()把所有输入转成小写,这样不管用户输入CHICAGO、ChIcAgO还是chicago,都会和预设的小写列表匹配成功
  • 友好的错误提示:把用户的原始输入回显在提示里,让用户清楚自己哪里输错了,体验更好
  • 返回值统一小写:函数返回的都是小写字符串,后续处理文件或筛选日期时,不用再处理大小写问题,逻辑更统一

扩展小技巧

如果需要支持数字月份/日期(比如输入1代表一月,2代表二月),可以修改合法列表并做简单的映射,比如:

# 支持数字+英文月份
valid_months = ['all', '1', '2', '3', '4', '5', '6', 'january', 'february', 'march', 'april', 'may', 'june']
# 或者把数字转成对应英文,方便后续处理
month_mapping = {'1':'january', '2':'february', '3':'march', '4':'april', '5':'may', '6':'june'}
if month in month_mapping:
    month = month_mapping[month]

内容的提问来源于stack exchange,提问作者LOR121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:31:41