如何用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
相关产品推荐
相关产品推荐

