如何实现按用户指定类型从JSON文件随机选取影片?
解决方法:根据用户输入的影片类型随机推荐影片
Hey there! Let's get this working for you—you've already got the basics down with loading the JSON file, so we just need to add a few key pieces to make the user input and random selection work properly.
问题分析
Your original code loops through all films and prints them, but to pick a random one by category, we need to:
- Get the user's desired category input
- Filter the films list to only include matches for that category
- Use
random.choice()on the filtered list (and handle cases where no matches exist, so we don't get errors!)
修改后的完整代码
import random import json # 获取用户输入的影片类型,加个清晰的提示 user_category = input("请输入你想选择的影片类型:").strip() # 加载JSON数据 with open('robot.json') as f: data = json.load(f) # 过滤出对应分类的影片——转成小写是为了避免大小写不匹配(比如用户输"科幻"和JSON里的"科幻",或者"Sci-Fi" vs "sci-fi") matching_films = [film for film in data['films'] if film["category"].lower() == user_category.lower()] # 先检查有没有匹配的影片,再随机选择 if matching_films: selected_film = random.choice(matching_films) print(f"为你推荐的影片:{selected_film['title']}(类型:{selected_film['category']})") else: print(f"抱歉,没有找到类型为'{user_category}'的影片哦!")
关键细节说明
- 列表推导式过滤:
[film for film in data['films'] if ...]这行快速筛选出所有和用户输入类型匹配的影片,转成小写是为了提升用户体验,不用严格匹配大小写。 - 空列表判断:如果用户输入的类型不存在,
matching_films会是空列表,直接用random.choice()会报错,所以先判断列表是否非空再执行随机选择。 - JSON结构要求:确保你的
robot.json结构是正确的,比如每个影片条目都有title和category字段,示例结构如下:
{ "films": [ {"title": "机器人总动员", "category": "动画"}, {"title": "终结者", "category": "科幻"}, {"title": "变形金刚", "category": "科幻"} ] }
这个代码应该能完美实现你想要的功能啦!如果还有其他问题,随时问~
内容的提问来源于stack exchange,提问作者Swan
相关产品推荐
相关产品推荐

