Home_work

0

Описание

«Открытие и чтение файла, запись в файл»

Языки

  • Python100%
год назад
год назад
год назад
README.md

Home_work

def read_recipes_file(recipes): with open(recipes, 'r', encoding='utf-8') as f: lines = [line.strip() for line in f] blocks = [] current_block = [] for line in lines: if line == '': if current_block: blocks.append(current_block) current_block = [] else: current_block.append(line) if current_block: blocks.append(current_block) return blocks

def parse_recipe_block(block): if len(block) < 2: return None name = block[0] try: n_ingredients = int(block[1]) except ValueError: return None if len(block) < 2 + n_ingredients: return None ingredients_lines = block[2:2 + n_ingredients] ingredients = [] for line in ingredients_lines: parts = [part.strip() for part in line.split('|')] if len(parts) != 3: continue ingredient_name, quantity_str, measure = parts try: quantity = int(quantity_str) except ValueError: try: quantity = float(quantity_str) except ValueError: continue ingredients.append({ 'name': ingredient_name, 'quantity': quantity, 'measure': measure }) return { 'name': name, 'ingredients': ingredients }

def get_recipes(file_name): blocks = read_recipes_file(file_name) recipes = [] for block in blocks: recipe = parse_recipe_block(block) if recipe: recipes.append(recipe) return recipes

if name == 'main': recipes = get_recipes('recipes.txt') for recipe in recipes: print(f'Блюдо: {recipe["name"]}') print('Ингредиенты:') for ingredient in recipe['ingredients']: print(f'- {ingredient["name"]} {ingredient["quantity"]} {ingredient["measure"]}') print()