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

Python遍历食谱TXT文件提取所有食材列表的实现问题

提取食谱文件中所有食材的解决方案

我来帮你搞定这个食材提取的需求!你的思路方向是对的,不过还需要加个状态标记来跟踪是否正在收集食材,这样就能精准抓取每个食谱里的食材内容,不会把其他章节的内容混进去。

核心思路

我们需要用一个布尔变量来标记当前是否处于食材章节:

  • 当遇到-Ingredients开头的行时,开启收集状态
  • 在收集状态下,把每一行食材内容加入列表,直到遇到下一个章节(比如Preperation、Description这类首字母大写的章节标题),就关闭收集状态

完整实现代码

import os
import sys

def get_ingredients_from_file():
    final_ingredients_list = []
    # 用with语句安全打开文件,自动处理文件关闭,避免资源泄漏
    with open("/Filepath/recipes.txt", "r") as recipe_file:
        in_ingredients_section = False
        for line in recipe_file:
            # 清理每行的换行符、前后空格,方便后续判断
            stripped_line = line.strip()
            
            # 触发食材章节的开始
            if stripped_line.startswith("-Ingredients"):
                in_ingredients_section = True
                continue  # 跳过标题行本身,不加入食材列表
            
            # 如果正处于食材收集状态
            if in_ingredients_section:
                # 判断是否到达下一个章节:这里假设章节名首字母大写(比如Preperation:)
                # 你可以根据实际文件结构调整这个判断条件,比如指定具体章节名
                if stripped_line and stripped_line[0].isupper():
                    in_ingredients_section = False
                else:
                    # 只添加非空行,避免列表里出现空内容
                    if stripped_line:
                        final_ingredients_list.append(stripped_line)
    return final_ingredients_list

# 测试函数调用
if __name__ == "__main__":
    all_ingredients = get_ingredients_from_file()
    print("整理好的食材列表:")
    for ingredient in all_ingredients:
        print(f"- {ingredient}")

代码关键点说明

  • 安全的文件操作:用with语句打开文件,无需手动调用close(),程序会自动处理文件关闭,避免资源浪费。
  • 状态跟踪:in_ingredients_section变量精准控制何时收集内容,不会误抓其他章节。
  • 内容清理:strip()方法去掉每行的多余空白,保证食材内容干净整洁。
  • 灵活的章节判断:当前用首字母大写识别下一个章节,你可以根据你的txt文件实际结构,改成更精准的判断(比如if stripped_line.startswith("Preperation:"))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:36:40