社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

迭代txt文件python

henning • 5 年前 • 1347 次点击  

我正试图迭代一个简单的.txt文件,其中包含一系列的食谱。 我想要的是我的循环找到所有以-成分开始的部分,添加每一行成分 到一个列表中,继续下一组原料,并添加这些原料,直到我有一个完整的列表,包括 文件中的所有成分。一般的文件结构如下:

  • 意面沙拉
  • 说明: BLA BLA

  • 成分:

  • 成分1
  • 成分2
  • 成分3

  • 准备: BLA BLA BLA

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

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38635
 
1347 次点击  
文章 [ 5 ]  |  最新文章 5 年前
Highyard
Reply   •   1 楼
Highyard    6 年前
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

我还是个新手,但这会查找以“-成分”开头的行,然后检查以“*”开头的行是否会添加到您的食谱列表中。然后你可以用这个列表做任何事情。

Jizhou Yang
Reply   •   2 楼
Jizhou Yang    6 年前

如果您讨厌if s和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_ingredients()的说明如下:

  1. 将整个文件读取为文本。
  2. 从文本中提取“-成分:”和“-准备:”之间的所有文本。
  3. 创建所有成分的列表。此时列表中包含空行。
  4. 过滤掉空行。
  5. 把配料放回原处。

main()只是运行get_ingredients()和quickly(?)把配料打印出来。

Neven V.
Reply   •   3 楼
Neven V.    6 年前

怎么样:

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 不是在别的地方用的,我想你在这里不需要它们。

Skydt
Reply   •   4 楼
Skydt    6 年前

假设TXT文件中的所有部分都以“-”开头,您可以创建两个字符串标志,并将它们用作嵌套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

希望这有帮助。

Devesh Kumar Singh
Reply   •   5 楼
Devesh Kumar Singh    6 年前

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

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']]