/
vikklow
/
homework
Обзор
Документация
Войти
/
vikklow
/
homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
main.py
206 строк
6 KB
Viktoria
first_commit
12 дек 2025, 15:57
12 дек 2025, 15:57
baa3f09
Код
Авторство
О чём код?
import os def read_cook_book(file_name): cook_book = {} try: with open(file_name, 'r', encoding='utf-8') as file: content = file.read().strip() recipes = content.split('\n\n') for recipe in recipes: lines = recipe.strip().split('\n') if len(lines) < 2: continue dish_name = lines[0].strip() ing_count = int(lines[1].strip()) ingredients = [] for i in range(2, 2 + ing_count): if i < len(lines): parts = [part.strip() for part in lines[i].split('|')] if len(parts) == 3: ingredients.append({ 'ingredient_name': parts[0], 'quantity': int(parts[1]), 'measure': parts[2] }) cook_book[dish_name] = ingredients except FileNotFoundError: print(f"Файл {file_name} не найден!") return {} except Exception as e: print(f"Ошибка при чтении файла: {e}") return {} return cook_book def get_shop_list_by_dishes(dishes, person_count, cook_book): shop_list = {} for dish in dishes: if dish in cook_book: for ingredient in cook_book[dish]: ing_name = ingredient['ingredient_name'] measure = ingredient['measure'] quantity = ingredient['quantity'] * person_count if ing_name in shop_list: shop_list[ing_name]['quantity'] += quantity else: shop_list[ing_name] = { 'measure': measure, 'quantity': quantity } return shop_list def merge_files(input_dir='files_to_merge', output_file='result.txt'): if not os.path.exists(input_dir): print(f"Директория '{input_dir}' не найдена!") print("Создайте папку 'files_to_merge' с файлами 1.txt, 2.txt, 3.txt") return files_to_merge = [] for file_name in os.listdir(input_dir): if file_name.endswith('.txt'): file_path = os.path.join(input_dir, file_name) files_to_merge.append(file_path) if not files_to_merge: print(f"В папке '{input_dir}' нет .txt файлов") return files_info = [] for file_path in files_to_merge: try: with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() content = ''.join(lines).rstrip('\n') files_info.append({ 'name': os.path.basename(file_path), 'path': file_path, 'line_count': len(lines), 'content': content }) except Exception as e: print(f"Ошибка при чтении файла {file_path}: {e}") files_info.sort(key=lambda x: x['line_count']) try: with open(output_file, 'w', encoding='utf-8') as result_file: for i, file_info in enumerate(files_info): result_file.write(f"{file_info['name']}\n") result_file.write(f"{file_info['line_count']}\n") result_file.write(file_info['content']) if i < len(files_info) - 1: result_file.write("\n\n") print(f" Файлы успешно объединены в '{output_file}'") print(f" Объединено {len(files_info)} файлов") print("\n Порядок объединения:") for file_info in files_info: print(f" {file_info['name']} ({file_info['line_count']} строк)") except Exception as e: print(f" Ошибка при записи результата: {e}") def print_cook_book(cook_book): print("\nЗадание №1") print("\nСловарь рецептов:") for dish, ingredients in cook_book.items(): print(f"\n{dish}:") for ing in ingredients: print(f" {ing['ingredient_name']} - {ing['quantity']} {ing['measure']}") def print_shop_list(shop_list): print("\nСписок покупок:") total_items = 0 for ingredient, details in shop_list.items(): print(f" {ingredient}: {details['quantity']} {details['measure']}") total_items += 1 print(f"\nВсего ингредиентов: {total_items}") def print_result_file(): if os.path.exists('result.txt'): print("\nСодержимое result.txt:") with open('result.txt', 'r', encoding='utf-8') as f: print(f.read()) def check_files_exist(): files_to_check = [ ('recipes.txt', 'Файл с рецептами'), ('files_to_merge/1.txt', 'Файл для объединения 1'), ('files_to_merge/2.txt', 'Файл для объединения 2'), ('files_to_merge/3.txt', 'Файл для объединения 3') ] all_exist = True for file_path, description in files_to_check: if os.path.exists(file_path): print(f"{description}: '{file_path}' - найден") else: print(f"{description}: '{file_path}' - не найден!") all_exist = False return all_exist def main(): cook_book = read_cook_book('recipes.txt') if cook_book: print(f"Успешно прочитано {len(cook_book)} рецептов") print_cook_book(cook_book) else: print("Не удалось прочитать словарь рецептов") return print("\nЗадание №2") dishes = ['Омлет', 'Запеченный картофель'] person_count = 2 print(f"\nБлюда: {', '.join(dishes)}") print(f"Количество персон: {person_count}") shop_list = get_shop_list_by_dishes(dishes, person_count, cook_book) print_shop_list(shop_list) print("\nЗадание №3") merge_files('files_to_merge', 'result.txt') print_result_file() if __name__ == "__main__": main()