/
sitdgo
/
Netology_Files_Homework
Обзор
Документация
Войти
/
sitdgo
/
Netology_Files_Homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
main.py
101 строка
3 KB
aleksandr Br
Netology_Files_Homework
14 дек 2025, 11:24
14 дек 2025, 11:24
573bb1d
Код
Авторство
О чём код?
import os def get_cook_book(file_name): cook_book = {} with open(file_name, encoding='utf-8') as file: while True: dish_name = file.readline().strip() if not dish_name: break ingredients_count_line = file.readline().strip() if not ingredients_count_line: break ingredients_count = int(ingredients_count_line) ingredients_list = [] for _ in range(ingredients_count): line = file.readline().strip() parts = line.split(' | ') ingredient = { 'ingredient_name': parts[0], 'quantity': int(parts[1]), 'measure': parts[2] } ingredients_list.append(ingredient) cook_book[dish_name] = ingredients_list file.readline() return cook_book def get_shop_list_by_dishes(dishes, person_count, cook_book): shop_list = {} for dish in dishes: if dish not in cook_book: print(f'Блюдо "{dish}" отсутствует в кулинарной книге.') continue for ingredient in cook_book[dish]: name = ingredient['ingredient_name'] quantity = ingredient['quantity'] * person_count measure = ingredient['measure'] if name in shop_list: shop_list[name]['quantity'] += quantity else: shop_list[name] = { 'measure': measure, 'quantity': quantity } return shop_list def combine_files(file_list, output_file_name): file_data = [] for file_name in file_list: try: with open(file_name, 'r', encoding='utf-8') as file: lines = file.readlines() file_data.append({ 'name': file_name, 'line_count': len(lines), 'content': "".join(lines) }) except FileNotFoundError: print(f'Файл {file_name} не найден и пропущен.') sorted_files = sorted(file_data, key=lambda x: x['line_count']) with open(output_file_name, 'w', encoding='utf-8') as output_file: for data in sorted_files: output_file.write(data['name'] + '\n') output_file.write(str(data['line_count']) + '\n') output_file.write(data['content']) if __name__ == '__main__': # Выполнение Задачи №1 cook_book = get_cook_book('recipes.txt') print('--- Задача №1: Книга рецептов ---') print(cook_book.get('Фахитос')) dishes_to_cook = ['Запеченный картофель', 'Омлет'] person_count = 2 shop_list = get_shop_list_by_dishes(dishes_to_cook, person_count, cook_book) print('\n--- Задача №2: Список покупок ---') print(f'Для {person_count} персон:') print(shop_list) files_to_combine = ['1.txt', '2.txt', '3.txt'] output_name = 'combined.txt' combine_files(files_to_combine, output_name) print(f'\n--- Задача №3: Объединение файлов ---') print(f'Файлы {", ".join(files_to_combine)} успешно объединены и отсортированы в {output_name}.') print('\n--- Содержимое combined.txt (для проверки) ---') with open(output_name, 'r', encoding='utf-8') as f: print(f.read())