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

如何用Python提取食谱文件中指定关键词区间内的内容?

提取食谱中食材行的解决方案

你的现有代码仅能返回Ingredients:之后的第二行,且未处理到Instructions:就停止,无法获取全部食材行。以下是正确的实现方式:

代码实现

def extract_ingredients(file_path):
    ingredients = []
    collecting = False
    with open(file_path, 'r') as f:
        for line in f:
            stripped_line = line.strip()
            if stripped_line == 'Ingredients:':
                collecting = True
                continue
            if stripped_line == 'Instructions:':
                collecting = False
                break
            if collecting and stripped_line:
                ingredients.append(stripped_line)
    return ingredients

# 使用示例
ingredients_list = extract_ingredients('recipes.txt')
for item in ingredients_list:
    print(item)

逻辑说明

  • 用collecting布尔变量标记是否进入食材行收集状态
  • 遍历文件每一行时先去除首尾空白字符
  • 遇到Ingredients:时开启收集状态并跳过当前行
  • 遇到Instructions:时关闭收集状态并终止循环
  • 收集状态开启时,将非空行(避免空行干扰)加入食材列表

针对你提供的示例文本,运行代码后会输出:

spaghetti: 200-g
butter: 25-gr
black pepper: as needed
pecorino: 50-gr

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:22:03