Python程序birthday_021.py功能优化求助:如何添加对应生日星期的诗歌内容输出
如何将出生日期对应的星期诗歌语句添加到Python程序输出中?
我来帮你搞定这个需求!要实现把对应星期的诗歌语句整合到输出里,我们可以通过建立星期与诗歌句子的映射字典,再扩展代码支持多行输入处理来完成。下面是完整的可运行代码:
#!/usr/bin/env python3 import datetime import calendar def get_birthday_poem(weekday): # 用字典存储星期和对应诗歌句子的映射,查找效率高且代码简洁 weekday_poems = { "Monday": "Monday’s child is fair of face", "Tuesday": "Tuesday’s child is full of grace", "Wednesday": "Wednesday’s child is full of woe", "Thursday": "Thursday’s child has far to go", "Friday": "Friday’s child is loving and giving", "Saturday": "Saturday’s child works hard for a living", "Sunday": "Sunday’s child is fair and wise and good in every way" } return weekday_poems.get(weekday, "") def find_day(date_str): # 解析日期字符串,返回星期几的全称(遵循Python命名规范,改用小写加下划线) born = datetime.datetime.strptime(date_str, '%d %m %Y').weekday() return calendar.day_name[born] def main(): print("请输入多行出生日期(每行格式:日 月 年),输入完成后按Ctrl+D(Linux/macOS)或Ctrl+Z(Windows)结束:") import sys # 遍历标准输入的每一行,处理多行输入 for line in sys.stdin: cleaned_line = line.strip() if not cleaned_line: continue # 跳过空行,避免无效处理 try: weekday = find_day(cleaned_line) poem_line = get_birthday_poem(weekday) # 使用f-string拼接输出,格式更清晰易读 print(f"You were born on a {weekday} and {poem_line}") except ValueError: # 捕获日期格式错误,给用户友好提示 print(f"❌ 错误:输入的日期格式不正确,请检查 '{cleaned_line}'") if __name__ == "__main__": main()
关键修改点说明
- 星期-诗歌映射字典:用
weekday_poems字典把每个星期几和对应的诗歌句子绑定,相比一堆if-elif判断,这种方式代码更简洁,查找速度也更快。 - 支持多行输入处理:通过遍历
sys.stdin读取每一行输入,自动处理用户输入的多行出生日期,同时跳过空行避免无效操作。 - 错误处理:加入
try-except捕获日期解析时的ValueError(比如输入的不是有效日期、格式不对),给用户明确的错误提示,让程序更健壮。 - 输出格式优化:使用Python的f-string来拼接输出内容,比原来的字符串加号拼接更直观,也更容易维护。
测试示例
如果输入:
26 11 2001 01 01 2024
程序会输出:
You were born on a Monday and Monday’s child is fair of face You were born on a Monday and Monday’s child is fair of face
内容的提问来源于stack exchange,提问作者Lostsoulaside
相关产品推荐
相关产品推荐

