Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 迭代txt文件_Python - Fatal编程技术网

Python 迭代txt文件

Python 迭代txt文件,python,Python,我正在尝试迭代一个简单的.txt文件,其中包含一组配方。 我想让我的循环找到以-配料开始的所有部分,添加每一行配料 在列表中,转到下一组配料并添加这些配料,直到我有一个完整的列表 文件中的所有成分。一般的文件结构如下所示: 意面沙拉 说明: 布拉 布拉 成分: 成分1 成分2 成分3 准备工作: 布拉 布拉 布拉 以下是迄今为止我的代码示例: import os import sys def get_ingredients_from_file(): recipe_file = open

我正在尝试迭代一个简单的.txt文件,其中包含一组配方。 我想让我的循环找到以-配料开始的所有部分,添加每一行配料 在列表中,转到下一组配料并添加这些配料,直到我有一个完整的列表 文件中的所有成分。一般的文件结构如下所示:

意面沙拉 说明: 布拉 布拉

成分:

成分1 成分2 成分3

准备工作: 布拉 布拉 布拉

以下是迄今为止我的代码示例:

import os
import sys

def get_ingredients_from_file():
    recipe_file = open("/Filepath/", "r")
    final_ingredients_list = list()

    for line in recipe_file:                                                                                   
        if line.startswith("-Ingredients"):                             
            # append every line until next section, then move on to next
            # ingredient section
那么:

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没有在其他地方使用,我认为这里不需要它们。

假设txt文件中的所有部分都以a开头-您可以创建两个字符串标志,并将它们用作嵌套for循环中的检查,如下所示:

import os
import sys

def get_ingredients_from_file():
  recipe_file = open("/Filepath/", "r")
  final_ingredients_list = list()
  string_flag1 = "-Ingredients"
  string_flag2 = "-"

  for line in recipe_file:                                                                                   
    if line.startswith(string_flag1):           #Line is ingredients
      for line in recipe_file:                  
        if not line.startswith(string_flag2):   #Loop until second string flag is encountered
          final_ingredients_list.append(line)   #append lines to the list
        else:
          break

希望这能有所帮助。

您可以使用临时列表添加配料,然后在遇到 一行-配料:,您将此列表附加到一个更大的列表,然后再次执行相同的操作

def get_ingredients_from_file():

    result = []
    with open('file.txt') as fp:
        li = []
        for line in fp:
            #Append the ingredients to temporary list
            if line.startswith('*'):
                li.append(line.replace('*','').strip())
            #Get a new list and append it to result
            elif line.startswith("- Ingredients"):
                li = []
                result.append(li)
    return result

print(get_ingredients_from_file())
所以如果文件看起来像

- Pasta Salad
- Description:
    bla
    bla

- Ingredients:
* ingredient 1
* ingredient 2
* ingredient 3

- Preperation:
    bla
    bla
    bla

- Ingredients:
* ingredient 4
* ingredient 5
* ingredient 6
输出将如下所示

[['ingredient 1', 'ingredient 2', 'ingredient 3'], 
['ingredient 4', 'ingredient 5', 'ingredient 6']]

如果你讨厌ifs和else,假设你只有一个成分部分,这里有一种使用正则表达式的方法

import re

def get_ingredients():
    text = open('recipe_test.txt', 'r').read()
    ingredients = re.search(r'- Ingredients:(.*?)- Preperation:', text, re.DOTALL).group(1)
    ingredients = ingredients.splitlines()
    ingredients = list(filter(lambda x: x, ingredients))
    return ingredients

def main():
    ingredients = get_ingredients()
    for ingredient in ingredients:
        print(ingredient)

if __name__ == '__main__':
    main()
get_成分说明如下:

将整个文件读入文本。 从文本中,提取-components:和-preposition:之间的所有文本 创建所有成分的列表。此时,列表包含空行。 过滤掉空行。 把配料退出来。 main just runs获取配料并整齐地打印出配料

def get_ingredients_from_file():
  recipe_file = open("/Filepath/", "r")
  recipe_text = recipe_file.readlines()
  recipe_list = []
  i = 1
  for line in recipe_text:
    if line.startswith('- Ingredients'):
      while recipe_text[recipe_text.index(line) + i].startswith('* '):
        recipe_list.append(recipe_text[recipe_text.index(line) + i])
        i += 1

我还是新手,但这将查找以-配料开头的行,然后检查以a*开头的行是否会添加到您的食谱列表中。然后,您可以对该列表执行任何操作。

您的文件是否包含要点?请将问题中的文件转换为与您正在阅读的文件完全匹配的代码块。请修复代码中的缩进。预期的输出是什么?请检查我下面的回答是否有意义@Henning您不能为这样打开的文件编制索引。而不重置我看起来是个错误。