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

如何使用Python读取txt文件的Master-Slave数据并存入Dictionary

Python解析txt生成目标字典的实现方法

实现逻辑

  • 初始化空字典存储结果
  • 逐行读取文本文件内容
  • 分割每行内容分别提取Master字段和Slave字段
  • 处理Slave字段为列表后存入字典

可直接运行的代码示例

假设你的文本文件名为data.txt,和Python脚本放在同目录下,代码如下:

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

# 只读模式打开文本文件
with open("data.txt", "r", encoding="utf-8") as file:
    # 遍历每一行内容
    for line in file:
        # 去除每行首尾的换行、空格等空白字符
        cleaned_line = line.strip()
        # 跳过空行
        if not cleaned_line:
            continue
        # 按"Slave : "分割为前后两部分
        master_section, slave_section = cleaned_line.split("Slave : ")
        # 提取Master值
        master_key = master_section.split("Master : ")[1].strip()
        # 处理Slave值为列表,自动过滤Slave后无值的空情况
        slave_value = [item for item in slave_section.split() if item]
        # 存入字典
        res[master_key] = slave_value

# 测试输出结果
print(res)

结果说明

运行代码后得到的res就是你需要的字典结构:

  • 有对应Slave的Master,值为Slave编号组成的字符串列表,比如"000000": ["000001", "000002"]
  • 没有对应Slave的Master,值为空列表[],符合Python数据处理的常规逻辑

如果你的文本文件不在脚本同目录,把代码里的"data.txt"替换为文件的绝对路径即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:54:03