私信  •  关注

Neven V.

Neven V. 最近创建的主题
Neven V. 最近回复了
6 年前
回复了 Neven V. 创建的主题 » 迭代txt文件python

怎么样:

def get_ingredients_from_file():
    recipe_file = open("./extractIngredients_input.txt", 'r')
    final_ingredients_list = list()
    add_ingredients = list()
    pick = False
    for line in recipe_file:
        if line.startswith("- Ingredients"):
            pick = True
            add_ingredients = list()
        elif line.startswith("-") and pick:
            pick = False
            final_ingredients_list.append(add_ingredients)
        elif pick and (len(line) > 1):
            add_ingredients.append(line[2:-1])
    if pick:
        final_ingredients_list.append(add_ingredients)
    return final_ingredients_list

它不完全是“每行追加到下一节,然后移到下一节” 成分部分的结构,但它工作得很好。

在另一张纸条上,如果 os sys 不是在别的地方用的,我想你在这里不需要它们。