/
Alexandr808
/
HomeworkOpeningFiles
Обзор
Документация
Войти
/
Alexandr808
/
HomeworkOpeningFiles
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
main.py
105 строк
3 KB
Alexandr
task 3
19 июн 2025, 09:59
19 июн 2025, 09:59
d5890e6
Код
Авторство
О чём код?
def read_recipes_from_file(filename): cook_book = {} with open(filename) as f: while True: dish_name = f.readline().strip() if not dish_name: break num_ingredients = int(f.readline()) ingredients = [] for _ in range(num_ingredients): line = f.readline().strip() ingredient_name, quantity, measure = map(str.strip, line.split('|')) ingredient = { 'ingredient_name': ingredient_name, 'quantity': int(quantity), 'measure': measure } ingredients.append(ingredient) cook_book[dish_name] = ingredients f.readline() return cook_book def get_shop_list_by_dishes(dishes, person_count): cook_book = read_recipes_from_file('recipes.txt') 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 import os def read_file_lines(filename): with open(filename) as f: lines = f.readlines() return [line.rstrip('\n') for line in lines] def merge_files(file_list, output_file): file_data = [] for filename in file_list: if not os.path.isfile(filename): print(f"Файл '{filename}' не найден. Пропускаем.") continue lines = read_file_lines(filename) file_data.append((os.path.basename(filename), len(lines), lines)) file_data.sort(key=lambda x: x[1]) with open(output_file, 'w') as out_file: for filename, line_count, lines in file_data: out_file.write(f"{filename}\n") out_file.write(f"{line_count}\n") for line in lines: out_file.write(f"{line}\n") out_file.write("\n") # def main(): # Задание №1 # cook_book = read_recipes_from_file('recipes.txt') # # for dish, ingredients in cook_book.items(): # print(f"{dish}:") # for item in ingredients: # print(f" {item}") # print() # def main(): # Задание №2 # cook_book = read_recipes_from_file('recipes.txt') # dishes = list(cook_book.keys()) # result = get_shop_list_by_dishes(dishes, 5) # # for ingredient, data in result.items(): # print(f"{ingredient}: {data}") def main(): # Задание №3 folder_path = 'Task3' input_files = ['songs.txt', 'bibliography.txt'] input_files = [os.path.join(folder_path, filename) for filename in input_files] output_file = 'result.txt' merge_files(input_files, output_file) print(f"Файлы из папки '{folder_path}' успешно объединены в '{output_file}'") if __name__ == "__main__": main()