Python新手求助:如何将文本文件转换为指定格式的嵌套Dictionary
将特定格式文本文件转换为嵌套字典(Python)
我是Python初学者,需要帮助将特定格式的文本文件转换为嵌套字典。
文本文件内容:
espresso, ingredients, water, 50, coffee, 18, cost, 1.5 latte, ingredients, water, 200, milk, 150, coffee, 24, cost, 2.5 cappuccino, ingredients, water, 250, milk, 100, coffee, 4, cost, 3.0
期望输出:
MENU = {"espresso": {"ingredients": {"water": 50, "coffee": 18}, "cost": 1.5}, "latte": {"ingredients": {"water": 200, "milk": 150, "coffee": 24}, "cost": 2.5}, "cappuccino": {"ingredients": {"water": 250, "milk": 100, "coffee": 4}, "cost": 3.0}}
已编写的代码:
def open_file() -> IO: """ Ask the user for the input menu file and open it """ file_pointer = None # prompts the user to enter a file name until a valid file is entered while file_pointer is None: # prompts the user to enter a file name file_name = input("Please enter a menu file: ") # try to open the file try: file_pointer = open(file_name, "r") # display an error message if cannot open file except IOError: print("An error has occurred, please try again. ") return file_pointer def create_menu(fp: IO) -> Dict [str, Dict [str, float]]: """ Creates a menu based on the inputted file in the form of a nested Dict """ MENU = {} for line in fp: drink_detail = line.strip().split()
补全后的完整代码:
from typing import IO, Dict def open_file() -> IO: """ Ask the user for the input menu file and open it """ file_pointer = None # prompts the user to enter a file name until a valid file is entered while file_pointer is None: # prompts the user to enter a file name file_name = input("Please enter a menu file: ") # try to open the file try: file_pointer = open(file_name, "r") # display an error message if cannot open file except IOError: print("An error has occurred, please try again. ") return file_pointer def create_menu(fp: IO) -> Dict[str, Dict[str, float]]: """ Creates a menu based on the inputted file in the form of a nested Dict """ MENU = {} for line in fp: # 按逗号分割文本,并去除每个元素的多余空格 drink_detail = [item.strip() for item in line.strip().split(',')] # 提取饮品名称作为外层字典的键 drink_name = drink_detail[0] # 初始化当前饮品的嵌套字典结构 drink_dict = {"ingredients": {}} i = 1 while i < len(drink_detail): current_key = drink_detail[i] if current_key == "ingredients": # 遍历处理食材组:每两个元素为一组(食材名+数量) i += 1 while i < len(drink_detail) and drink_detail[i] != "cost": ingredient = drink_detail[i] amount = int(drink_detail[i+1]) drink_dict["ingredients"][ingredient] = amount i += 2 elif current_key == "cost": # 处理价格,转换为浮点数 drink_dict["cost"] = float(drink_detail[i+1]) i += 2 # 将当前饮品字典加入总菜单 MENU[drink_name] = drink_dict return MENU # 测试执行 if __name__ == "__main__": file = open_file() menu_result = create_menu(file) file.close() print("MENU =", menu_result)
关键逻辑说明:
- 文本分割修正:原文本用逗号分隔,所以改用逗号分割后再清理每个元素的空格,避免因空格导致的解析错误。
- 分层解析:先提取饮品名,再分别处理
ingredients和cost模块,食材部分按"名称-数量"的成对规则解析,价格单独转换为浮点数。 - 类型转换:将食材数量转为整数、价格转为浮点数,匹配期望输出的类型要求。
内容的提问来源于stack exchange,提问作者lnhmai
相关产品推荐
相关产品推荐

