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

Python根据名字首字母输出对应赞美语的代码问题求助

问题解决与实现指南

一、修复代码无输出的问题

错误原因

原代码的判断逻辑完全错误:if input_name[0:1] == warm_fuzzies[n1] 是把名字的首字母和字典中'a'对应的赞美语字符串做比较,这永远不会相等,因此不会执行print语句。另外未处理首字母大写的情况,比如用户输入"Alice",首字母是'A',但字典键是小写的'a',也会匹配失败。

修正后的代码

# Warm fuzzies
def main():
    warm_fuzzies = {
        'a': "You're irresistible when you blush.",
        'b': "How is it that you always look great, even in sweatpants?",
        'c': "You have the best ideas.",
        'd': "Everyone gets knocked down sometimes, but you always get back up and keep going.",
        'e': "You are a gift to those around you.", 
        'f': "You are all that and a super-size bag of chips.", 
        'g': "You are even more beautiful on the inside than you are on the outside.", 
        'h': "That thing you do not like about yourself is what makes you so interesting.",
        'i': "You are like a breath of fresh air.", 
        'j': "You are someone's reason to smile.", 
        'k': "You're even better than a unicorn, because you're real.",
        'l': "You're really something special.", 
        'm': "You deserve a hug right now.",
        'n': "If someone based an Internet meme on you, it would have impeccable grammar.",
        'o': "Being around you makes everything better!",
        'p': "You're better than a triple-scoop ice cream cone. With sprinkles.", 
        'q': "You should be thanked more often. So thank you!!",
        'r': "You're a great example to others.",
        's': "Your kindness is a balm to all who encounter it.",
        't': "When you make up your mind about something, nothing stands in your way.", 
        'u': "The way you treasure your loved ones is incredible.",
        'v': "You're an awesome friend to those around you.", 
        'w': "You're a gift to those around you.", 
        'x': "When I'm down you always say something encouraging to help me feel better.",
        'y': "When I'm down you always say something encouraging to help me feel better.", 
        'z': "Our community is better because you're in it."
    }
    print('What is your name?')
    input_name = input('Insert name here: ')
    
    # 提取首字母并转为小写,兼容大写输入
    first_char = input_name.strip()[0].lower()
    
    # 检查首字母是否在字典中,存在则输出对应赞美语
    if first_char in warm_fuzzies:
        print(warm_fuzzies[first_char])
    else:
        print("Sorry, we don't have a warm fuzzy for your initial yet!")

main()

关键改进点

  • 提取名字首字母后转为小写,确保不管用户输入大写还是小写首字母都能匹配
  • 直接检查首字母是否在字典的键中,无需逐个判断每个字母,逻辑更简洁
  • 增加无匹配时的提示,避免静默无输出的情况

二、从.txt文件导入数据到字典

步骤1:准备txt文件

创建一个warm_fuzzies.txt文件,每行格式为字母:赞美语,示例内容:

a:You're irresistible when you blush.
b:How is it that you always look great, even in sweatpants?
c:You have the best ideas.

步骤2:编写读取代码

def load_warm_fuzzies_from_file(file_path):
    warm_fuzzies = {}
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 去掉每行首尾的空白字符(换行、空格等)
            line = line.strip()
            # 跳过空行
            if not line:
                continue
            # 分割字母和赞美语,只分割一次(避免赞美语里有冒号的情况)
            key, value = line.split(':', 1)
            # 把字母转为小写,确保匹配时不区分大小写
            warm_fuzzies[key.lower()] = value.strip()
    return warm_fuzzies

def main():
    # 从文件加载字典
    warm_fuzzies = load_warm_fuzzies_from_file('warm_fuzzies.txt')
    print('What is your name?')
    input_name = input('Insert name here: ')
    
    first_char = input_name.strip()[0].lower()
    if first_char in warm_fuzzies:
        print(warm_fuzzies[first_char])
    else:
        print("Sorry, we don't have a warm fuzzy for your initial yet!")

main()

说明

  • 使用with open()语句自动管理文件关闭,避免资源泄漏
  • 用split(':', 1)只分割一次,防止赞美语中包含冒号导致出错
  • 读取时将键转为小写,保持和用户输入处理逻辑一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:00:32