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

如何将食谱文本文件转换为Python字典列表?求实现方案

问题:如何将食谱文本文件转换为指定的字典列表格式?

我有一个包含多份食谱的文本文件,想知道有没有简便方法把它转换成下面load_data()函数返回的字典列表格式。如果没有简便方法,是不是只能逐行遍历文本、在特定位置拆分来构建列表和字典结构?

文本文件内容:

name:Chocolate Chip Cookies
categories:dessert;cookie;chocolate
ingredient:2¼ cups all-purpose flour
ingredient:1 teaspoon baking soda
ingredient:1 teaspoon salts
ingredient:½ cup (1 stick) butter, softened
ingredient:¾ cup granulated sugar
ingredient:¾ cup packed brown sugar
ingredient:1 teaspoon vanilla extract
ingredient:2 large eggs
ingredient:2 cups (12-ounce package) Semi-Sweet Chocolate Chips
step:Preheat oven to 375°F
step:Combine flour, baking soda, and salt in a small bowl.
step:Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.
step:Add eggs, beating well after each addition.
step:Gradually beat the flour mixture into the wet mixture.
step:Stir in morsels.
step:Drop rounded tablespoons of dough onto ungreased baking sheets.
step:Bake for 9 to 11 minutes or until golden brown.
step:Cool on baking sheets for 2 minutes.
step:Move to wire racks to cool completely.
name:Sugar Cookies
categories:dessert;cookie;kid's favorites
ingredient:2¾ cups all-purpose flour
ingredient:1 teaspoon baking soda
ingredient:½ teaspoon baking powder
ingredient:1 cup butter, softened
ingredient:1½ cups white sugar
ingredient:1 egg
ingredient:1 teaspoon vanilla extract 
step:Preheat oven to 375°F
step:In a small bowl, stir together flour, baking soda, and baking powder. Set aside.
step:In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.
step:Blend the wet and dry ingredients.
step:Place teaspoon-size balls of dough onto an ungreased cookie sheet.
step:Bake 8 to 10 minutes in the preheated oven, or until golden.
step:Let stand on cookie sheet two minutes before removing to cool on wire racks.

目标格式(load_data()返回值):

def load_data():
    return [
        {
            'name': 'Chocolate Chip Cookies',
            'categories': ['dessert', 'cookie', 'chocolate'],
            'ingredients': ['2¼ cups all-purpose flour',
                            '1 teaspoon baking soda',
                            '1 teaspoon salts',
                            '½ cup (1 stick) butter, softened',
                            '¾ cup granulated sugar',
                            '¾ cup packed brown sugar',
                            '1 teaspoon vanilla extract',
                            '2 large eggs',
                            '2 cups (12-ounce package) Semi-Sweet Chocolate Chips'],
            'steps': ['Preheat oven to 375°F',
                      'Combine flour, baking soda, and salt in a small bowl.',
                      'Beat butter, sugar, brown sugar, and vanilla extract in a large bowl until creamy.',
                      'Add eggs, beating well after each addition.',
                      'Gradually beat the flour mixture into the wet mixture.',
                      'Stir in morsels.',
                      'Drop rounded tablespoons of dough onto ungreased baking sheets.',
                      'Bake for 9 to 11 minutes or until golden brown.',
                      'Cool on baking sheets for 2 minutes.',
                      'Move to wire racks to cool completely.']
        },
        {
            'name': 'Sugar Cookies',
            'categories': ['dessert', 'cookie', "kid's favorites"],
            'ingredients': ['2¾ cups all-purpose flour',
                            '1 teaspoon baking soda',
                            '½ teaspoon baking powder',
                            '1 cup butter, softened',
                            '1½ cups white sugar',
                            '1 egg',
                            '1 teaspoon vanilla extract'],
            'steps': ['Preheat oven to 375°F',
                      'In a small bowl, stir together flour, baking soda, and baking powder. Set aside.',
                      'In a large bowl, mix together butter and sugar until smooth. Beat in egg and vanilla.',
                      'Blend the wet and dry ingredients.',
                      'Place teaspoon-size balls of dough onto an ungreased cookie sheet.',
                      'Bake 8 to 10 minutes in the preheated oven, or until golden.',
                      'Let stand on cookie sheet two minutes before removing to cool on wire racks.']
        }
    ]

解决方案

不用逐行硬拆,根据文本的结构规律,可以用简洁的方式处理。核心思路是按食谱分隔(遇到name:开头的行就新建一个食谱字典),然后对每行按冒号拆分键值,再做对应处理:

代码实现

def parse_recipe_file(file_path):
    recipes = []
    current_recipe = None
    
    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)
            
            if key == 'name':
                # 遇到新食谱,保存上一个(如果有的话)
                if current_recipe is not None:
                    recipes.append(current_recipe)
                # 初始化新食谱字典
                current_recipe = {
                    'name': value.strip(),
                    'categories': [],
                    'ingredients': [],
                    'steps': []
                }
            elif key == 'categories':
                # 分号分割转列表
                current_recipe['categories'] = [cat.strip() for cat in value.split(';')]
            elif key == 'ingredient':
                current_recipe['ingredients'].append(value.strip())
            elif key == 'step':
                current_recipe['steps'].append(value.strip())
    
    # 把最后一个食谱加入列表
    if current_recipe is not None:
        recipes.append(current_recipe)
    
    return recipes

使用说明

调用这个函数并传入你的食谱文件路径,就能得到和load_data()一致的字典列表:

# 示例调用
recipe_data = parse_recipe_file('recipes.txt')
# 可以直接替换原load_data函数的返回值
def load_data():
    return parse_recipe_file('recipes.txt')

逻辑说明

  1. 遍历文件每一行,跳过空行
  2. 遇到name:开头的行,创建新的食谱字典,同时把之前的食谱存入列表
  3. 对categories行,用分号分割成列表
  4. 对ingredient和step行,直接把内容追加到对应的列表中
  5. 遍历结束后,把最后一个食谱加入列表

这种方法既简洁又符合文本的结构规律,比逐行硬拆更易维护。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:50:46