/
Deshead
/
Homework_Read_files
Обзор
Документация
Войти
/
Deshead
/
Homework_Read_files
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
main.py
99 строк
3 KB
Deshead
upload files
19 июн 2025, 17:36
19 июн 2025, 17:36
1d537a3
Код
Авторство
О чём код?
#Задача 1 def get_dict(string): blocks = [b.strip() for b in string.split('\n\n') if b.strip()] cook_dict = {} for block in blocks: lines = block.split('\n') dish = lines[0] try: count = int(lines[1]) except (ValueError, IndexError): continue ingredients = [] for i in range(2, 2 + count): if i >= len(lines): break parts = lines[i].split(' | ') if len(parts) < 3: continue ingredient = { 'ingredient_name': parts[0], 'quantity': parts[1], 'measure': parts[2] } ingredients.append(ingredient) cook_dict[dish] = ingredients return cook_dict with open('recipes.txt', 'r', encoding='utf-8') as f: txt = f.read() cook_book = get_dict(txt) cook_book.pop('Фахитос', None) for dish, ingredients in cook_book.items(): print(f"{dish}: [") for ing in ingredients: print( f" {{'ingredient_name': '{ing['ingredient_name']}', 'quantity': {ing['quantity']}, 'measure': '{ing['measure']}'}},") print("]\n") #Задача 2 from pprint import pprint cook_book = {} with open('recipes.txt', 'rt', encoding='utf-8') as file: dishes = '' for x in file: x = x.strip() if x.isdigit(): continue elif x and '|' not in x: cook_book[x] = [] dishes = x elif x and '|' in x: a, b, c = x.split(" | ") cook_book.get(dishes).append(dict(ingredient_name=a, quantity=int(b), measure=c)) def get_shop_list_by_dishes(dishes_list, person_count): shop_list = {} for dish in dishes_list: if dish in cook_book: for ingredient in cook_book[dish]: if ingredient['ingredient_name'] in shop_list: shop_list[ingredient['ingredient_name']]['quantity'] += ingredient['quantity'] * person_count else: shop_list[ingredient['ingredient_name']] = ({'measure': ingredient['measure'], 'quantity': (ingredient['quantity'] * person_count)}) else: print('Такого блюда нет в книге') return shop_list pprint(get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2)) #Задача 3 import os def count_lines(filepath): with open(filepath, 'r', encoding='utf-8') as f: return sum(1 for line in f) def merge_files_with_metadata(input_files, output_file): files_info = [] for filepath in input_files: lines = count_lines(filepath) files_info.append((lines, os.path.basename(filepath))) files_info.sort() with open(output_file, 'w', encoding='utf-8') as out_f: for lines, filename in files_info: out_f.write(f"{filename}\n{lines}\n") if __name__ == "__main__": input_files = ['1.txt', '2.txt', '3.txt'] output_file = 'result.txt' merge_files_with_metadata(input_files, output_file)