/
Kosmich1
/
Read_files
Обзор
Документация
Войти
/
Kosmich1
/
Read_files
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Cook_book.py
85 строк
3 KB
Kosmich1
upload files
24 мар 2025, 19:50
24 мар 2025, 19:50
a2f16a8
Код
Авторство
О чём код?
cook_book = {} with open('recipes.txt', 'r', encoding='utf-8') as f: list_dish = f.readlines() count = 0 while count < len(list_dish): dish_name = list_dish[count].strip().lower() count += 1 ingr_num = int(list_dish[count].strip()) count += 1 ingredients = [] for _ in range(ingr_num): ingredient_list = list_dish[count].strip().lower() count += 1 list_name_dish = ingredient_list.split(' | ') ingredients.append({ 'ingredient_name': list_name_dish[0], 'quantity': int(list_name_dish[1]), 'measure': list_name_dish[2] }) cook_book[dish_name] = ingredients if count < len(list_dish) and list_dish[count].strip() == '': count += 1 print("Книга рецептов:") print(cook_book) def get_shop_list_by_dishes(dishes, person_count): """Создаем список покупок по блюдам и количеству персон.""" shop_list = {} for dish in dishes: if dish not in cook_book: print(f'Ошибка: Блюдо "{dish}" не найдено в книге рецептов.') continue for ingredient in cook_book[dish]: new_shop_list_item = dict(ingredient) new_shop_list_item['quantity'] *= person_count if new_shop_list_item['ingredient_name'] not in shop_list: shop_list[new_shop_list_item['ingredient_name']] = new_shop_list_item else: shop_list[new_shop_list_item['ingredient_name']]['quantity'] += new_shop_list_item['quantity'] return shop_list def print_shop_list(shop_list): """Выводим список покупок в формате {ингредиент} {количество} {единица измерения}.""" print("\n🛒 Список покупок:") for shop_list_item in shop_list.values(): print(f'{shop_list_item["ingredient_name"]} {shop_list_item["quantity"]} {shop_list_item["measure"]}') def create_shop_list(): """Запрашиваем у пользователя блюда и количество персон, затем формирует список покупок.""" person_count = int(input('Введите количество человек: ')) dishes = input('Введите блюда (через запятую): ').lower().split(', ') shop_list = get_shop_list_by_dishes(dishes, person_count) print_shop_list(shop_list) # --- Запуск функции для списка покупок --- create_shop_list() # --- Читаем файлы и сортируем их по количеству строк --- files = ['1.txt', '2.txt', '3.txt'] file_lines = [] for file in files: try: with open(file, encoding='utf-8') as f: lines = f.readlines() file_lines.append((file, len(lines), lines)) except FileNotFoundError: print(f'Ошибка: Файл "{file}" не найден.') # Сортируем файлы по количеству строк sorted_files = sorted(file_lines, key=lambda x: x[1]) # Записываем в merged_file.txt with open('merged_file.txt', 'w', encoding='utf-8') as output_file: for file_name, line_count, lines in sorted_files: output_file.write(f'{file_name}\n{line_count}\n') output_file.writelines(lines) output_file.write('\n') print('\n Файл merged_file.txt создан!')