如何在Python中通过食材值打印对应食谱数组的名称
交互式食谱书问题解决方案
问题说明
需实现终端输入食材名称后,输出对应食谱名称的功能,现有JSON结构和Python代码存在缺陷,无法完成需求。
第一步:修正JSON结构
原JSON格式不规范,Recipes数组内混合了字符串与数组结构,会导致解析错误。建议将每个食谱定义为包含完整属性的对象,示例如下:
{ "Recipes": [ { "name": "chocolate chip cookie", "ingredients": ["flour", "sugar", "butter", "chocolate chips"], "instructions": "Step 1: Preheat Oven to 375", "category": "Cookies" }, { "name": "vanilla cake", "ingredients": ["flour", "egg", "milk", "vanilla extract"], "instructions": "Step 1: Preheat Oven to 350", "category": "Cakes" } ] }
注:将食材改为数组格式,便于后续匹配判断。
第二步:优化Python代码
原代码存在重复导入模块、重复读取文件的问题,且未实现食材匹配逻辑。以下是修正后的完整代码:
import json # 一次性读取食谱数据 with open('cookbook.json', 'r') as f: data = json.load(f) response = input("are you looking for recipes with ingredients on hand (if so please enter 'ingredients') or are you looking for something to cook/bake? (if so please enter 'Cook/Bake')\n") if response == "ingredients": print("please enter ingredients") ingredients_input = input("enter ingredients separated by commas: ") # 处理输入食材,去除空格并统一小写,避免匹配偏差 ingredients = [ing.strip().lower() for ing in ingredients_input.split(",")] matched_recipes = [] # 遍历所有食谱进行匹配 for recipe in data["Recipes"]: recipe_ingredients = [ing.lower() for ing in recipe["ingredients"]] # 检查输入食材是否有至少一个存在于当前食谱中 if any(ing in recipe_ingredients for ing in ingredients): matched_recipes.append(recipe["name"]) # 输出匹配结果 if matched_recipes: print("Matching recipes:") for name in matched_recipes: print(f"- {name}") else: print("No recipes found with the entered ingredients.")
代码关键优化点
- 将模块导入和文件读取放在循环外,避免重复操作提升效率
- 处理输入的食材格式,消除空格和大小写差异对匹配的影响
- 使用
any()函数快速判断食材匹配关系 - 收集并统一输出所有匹配的食谱名称,无匹配时给出提示
内容的提问来源于stack exchange,提问作者Cherrypie Delight
相关产品推荐
相关产品推荐

