You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中读取txt文件数据并转换为指定格式的嵌套字典

Python TXT转嵌套字典实现方案

无需修改现有txt文件结构,直接使用以下代码即可得到目标格式的字典:

# 初始化结果字典
pokemon = {}

# 读取txt文件,替换为你自己的文件路径
with open("pokemon.txt", "r", encoding="utf-8") as file:
    for line in file:
        # 去除首尾空白字符,跳过空行
        line = line.strip()
        if not line:
            continue
        # 按逗号拆分字段并去除各字段首尾空格
        name, quantity_str, fee_str, powers_str = [i.strip() for i in line.split(",")]
        # 组装嵌套字典
        pokemon[name] = {
            "quantity": int(quantity_str),
            "fee": int(fee_str),
            "powers": powers_str.split()
        }

执行完成后pokemon变量就是你要求的结构,直接调用即可。

内容的提问来源于stack exchange,提问作者Max Chi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:06:01