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

Python层级目录编码映射Excel及用户查询功能优化需求

解决方案:Excel层级编码映射目录结构与查询写入实现

一、统一编码格式处理

先把带空格和紧凑编码转换成统一的层级列表,方便后续目录树查询。以下是适配示例编码规则(前缀+单字符层级)的处理函数,可根据实际编码结构调整:

def normalize_code(code):
    if not isinstance(code, str):
        return []
    # 带空格编码按空格分割,紧凑编码拆分前缀+后续单个字符
    if " " in code:
        return [part.strip() for part in code.split() if part.strip()]
    else:
        return [code[0]] + list(code[1:]) if len(code) > 0 else []

二、修复编码-目录映射逻辑

定义基础的Directory类,用字典存储子节点(键为编码节点,值为目录实例),确保编码与目录名的准确映射:

class Directory:
    def __init__(self, name):
        self.name = name
        self.children = {}  # key: 编码节点值, value: Directory实例

    def add_child(self, code_node, dir_name):
        if code_node not in self.children:
            self.children[code_node] = Directory(dir_name)
        return self.children[code_node]

从Excel读取编码-目录对应关系,构建层级目录树,同时校验编码层级的连续性,避免映射错误:

from openpyxl import load_workbook

def build_directory_tree(excel_path):
    wb = load_workbook(excel_path)
    ws = wb.active
    root = Directory("根目录")  # 根节点名称可按需修改
    for row in ws.iter_rows(min_row=2, values_only=True):
        code_full, dir_name = row[0], row[1]
        if not code_full or not dir_name:
            continue
        code_parts = normalize_code(code_full)
        if not code_parts:
            continue
        current_node = root
        # 逐层遍历编码,确保父节点存在后再添加子节点
        for idx, part in enumerate(code_parts):
            if idx == len(code_parts) - 1:
                current_node.add_child(part, dir_name)
            else:
                if part not in current_node.children:
                    raise ValueError(f"编码 {code_full} 的父节点 {part} 不存在,请检查Excel数据完整性")
                current_node = current_node.children[part]
    return root

三、查询编码对应的完整层级路径

基于统一后的编码格式,遍历目录树获取完整路径:

import os

def get_full_path(root_dir, code):
    code_parts = normalize_code(code)
    if not code_parts:
        return "编码为空"
    current_node = root_dir
    path_components = []
    for part in code_parts:
        if part not in current_node.children:
            return "编码不存在"
        current_node = current_node.children[part]
        path_components.append(current_node.name)
    # 使用系统默认路径分隔符(如Windows的\,Linux的/)
    return os.sep.join(path_components)

四、将路径写入Excel对应列

读取目标Excel,批量处理编码并写入路径:

def write_paths_to_excel(input_excel, output_excel, root_dir):
    wb = load_workbook(input_excel)
    ws = wb.active
    # 在第三列新增"完整层级路径"表头,可根据实际调整列位置
    ws.cell(row=1, column=3, value="完整层级路径")
    for row_num in range(2, ws.max_row + 1):
        code = ws.cell(row=row_num, column=1).value
        path = get_full_path(root_dir, code)
        ws.cell(row=row_num, column=3, value=path)
    wb.save(output_excel)

示例调用

if __name__ == "__main__":
    # 替换为你的编码-目录映射Excel路径
    tree_excel = "directory_mapping.xlsx"
    # 替换为需要处理的目标Excel路径
    data_excel = "target_data.xlsx"
    output_excel = "data_with_paths.xlsx"

    try:
        root_tree = build_directory_tree(tree_excel)
        write_paths_to_excel(data_excel, output_excel, root_tree)
        print(f"处理完成,结果已保存至 {output_excel}")
    except Exception as e:
        print(f"出错:{str(e)}")

注意事项

  • 编码规则适配:normalize_code是核心函数,必须根据你的实际编码结构调整拆分逻辑(比如编码是"F010203"且每两位为一个层级,就改成按两位拆分)
  • 数据校验:构建目录树时会校验父节点是否存在,若Excel数据存在层级断层,会抛出错误,可按需改成自动创建空父节点或跳过该行
  • 列位置调整:代码中默认编码在第一列、路径写入第三列,可根据你的Excel结构修改column参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:26:19