/
Saku
/
HomeWorkWorkingWithFiles
Обзор
Документация
Войти
/
Saku
/
HomeWorkWorkingWithFiles
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
CookBook/main.py
146 строк
4 KB
Danil Kornilov
SecondCommit
21 апр 2025, 17:26
21 апр 2025, 17:26
aed66e5
Код
Авторство
О чём код?
def read_recipes(file_name): recipes = [] with open(file_name, 'r', encoding='utf-8') as file: while True: name = file.readline().strip() if not name: break ingredient_count = file.readline().strip() if not ingredient_count: break try: ingredient_count = int(ingredient_count) except ValueError: break ingredients = [] for _ in range(ingredient_count): ingredient_line = file.readline().strip() if not ingredient_line: break parts = [part.strip() for part in ingredient_line.split('|')] if len(parts) != 3: continue ingredient = { 'ingredient' : parts[0], 'quantity' : parts[1], 'measure' : parts[2] } ingredients.append(ingredient) recipe = {'name' : name, 'ingredients' : ingredients} recipes.append(recipe) file.readline() return recipes def print_recipe(recipe): print(f"\n{recipe['name']}") print('Ингредиенты:') for ing in recipe['ingredients']: print(f"- {ing['ingredient']} : {ing['quantity']} {ing['measure']}") def print_all_recipes(recipes): print("\nКулинарная книга") print("=============\n") for recipe in recipes: print_recipe(recipe) def find_recipe_by_name(recipes, name): for recipe in recipes: if recipe['name'].lower() == name.lower(): return recipe return None def get_shop_list_by_dishes(recipes, dishes, person_count): shop_list = {} for dish_name in dishes: recipe = find_recipe_by_name(recipes, dish_name) if not recipe: continue for ingredient in recipe['ingredients']: name = ingredient['ingredient'] measure = ingredient['measure'] try: quantity = float(ingredient['quantity']) * person_count except ValueError: quantity = ingredient['quantity'] if name in shop_list: try: shop_list[name]['quantity'] += quantity except TypeError: pass else: shop_list[name] = {'measure' : measure, 'quantity' : quantity} return shop_list def print_shop_list(shop_list): print('\nСписок покупок:') print('-----------') for item, data in shop_list.items(): print(f"{item}: {data['quantity']} {data['measure']}") def main(): try: recipes = read_recipes('recipes.txt') except FileNotFoundError: print('Ошибка: файл с рецептами не найден.') return if not recipes: print('В файле нет рецептов или он пуст.') return while True: print("\nМеню:") print("1. Показать все рецепты") print("2. Найти рецепт по названию") print("3. Создать список покупок для нескольких блюд") print("4. Выход") choice = input("Выберите действие: ") if choice == '1': print_all_recipes(recipes) elif choice == '2': name = input('Введите название блюда: ') recipe = find_recipe_by_name(recipes, name) if recipe : print_recipe(recipe) else: print("Рецепт не найде.") elif choice == '3': dish_names = input("Введите названия блюд через запятую: ").split(',') dish_names = [name.strip() for name in dish_names] try: person_count = int(input("Введите количество персон: ")) except ValueError: print("Ошибка: введите число") continue shop_list = get_shop_list_by_dishes(recipes, dish_names, person_count) print_shop_list(shop_list) elif choice == '4': print("До свидания!") break else: print("Неверный ввод. Попробуйте ещё раз.") if __name__ == '__main__': main()