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

如何从文本文件解析生成类层级并实现属性访问与运算?

层级属性结构的解析与运算实现方案

原始数据文件内容

name                      | value
_________________________________
a.attribute_1             | val_0
a.b.attribute_2           | val_1
a.b.attribute_3           | val_2
a.c.attribute_4           | val_3
a.c.d.attribute_5         | val_4
a.e.f.g.attribute_6       | val_5
a.e.f.h.attribute_7       | val_6

实现可行性与所需工具

完全可以实现这种层级类结构的创建、属性访问及基础运算,无需额外第三方工具,用Python标准库即可完成,核心依赖以下特性:

  • 动态属性操作:getattr()、setattr() 函数
  • 属性容器:自定义类或types.SimpleNamespace(标准库内置)
  • 字符串路径解析:str.split() 方法分割点分隔的层级路径

具体实现代码

1. 定义动态属性容器类

这个类会自动创建不存在的子属性,方便构建嵌套层级:

class AttrContainer:
    def __getattr__(self, name):
        # 访问未定义的属性时自动创建子容器
        setattr(self, name, AttrContainer())
        return getattr(self, name)

2. 解析文件并构建层级结构

读取文件内容,将name列的层级路径映射为属性结构,同时绑定对应变量值:

def parse_attr_file(file_path, var_values):
    root = AttrContainer()
    with open(file_path, 'r') as f:
        lines = f.readlines()
        # 跳过表头和分隔线,处理有效数据行
        for line in lines[2:]:
            line = line.strip()
            if not line:
                continue
            name_str, val_str = line.split('|')
            # 分割层级路径和变量名
            attr_path = name_str.strip().split('.')
            var_name = val_str.strip()
            
            # 遍历路径找到最内层容器
            current_node = root
            for node in attr_path[:-1]:
                current_node = getattr(current_node, node)
            # 给最终属性赋值
            setattr(current_node, attr_path[-1], var_values.get(var_name, 0))
    return root

3. 使用示例

# 定义变量值
var_dict = {
    'val_2': 6,
    'val_5': 2
}

# 解析文件得到层级对象
a = parse_attr_file('your_attr_file.txt', var_dict)

# 执行属性访问与运算
sum_result = a.e.f.g.attribute_6 + a.b.attribute_3
print(sum_result)  # 输出:8

替代简化方案

如果不想自定义类,可以用标准库的types.SimpleNamespace来实现属性容器,只需修改容器创建逻辑:

from types import SimpleNamespace

def get_or_create_namespace(parent, name):
    if not hasattr(parent, name):
        setattr(parent, name, SimpleNamespace())
    return getattr(parent, name)

# 对应修改parse_attr_file函数中的节点遍历逻辑即可

内容的提问来源于stack exchange,提问作者אור משעל

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:05:37