错误: `get_leaf_nodes` 在叶子节点上引发 KeyError, 这是因为 `nodes` 关键字缺失
作者: ChiragB254创建于 2026年6月16日更新于 2026年7月13日
□ 说明
get leaf nodes ()' inpageindex/utils.py' 中,在使用由标准管道所建造的树结构时,用KeyError'撞倒了。 函数直接取用结构['节点'',但叶子节点没有节点'键——在list to tree()'内用`clean node()'明确去掉。
□ 受影响的文件
pageindex/utils.py'-get leaf nodes' 函数
def get leaf nodes(结构):
如果存在( 结构, dict) :
如果不是结构 ['节点'] : # # keyError: “ 节点” 密钥在叶子节点上不存在
结构 节点=复制.deepcopy(结构)
结构 node. pop( “ nodes' , 无)
返回 [结构 节点]□ 根源
'List to tree ()' calls clean node ()',** 删除** 无子女任何节点的nodes'密钥:
[Python] clean node( 节点) : 如果不是节点['节点']: del 节点 ['nodes'] # QQ 密钥被完全去除, 不设置为 []
因此,当“get leaf nodes”以后在其中一个节点上检查“结构['nodes]”时,键就不复存在了,并提出了“KeyError”。
□ 步骤重现
```2ZZ
从 pageindex.utils 导入 获取 leaf 节点,列表 to tree
平方 = [
{'结构':'1','标题':'第一章','起始 index':1,'end index':5},
{'结构':'2','标题':'第2章','开始 index':6,'end index':10},
[ . ]
树 = 列表 to tree(平面) # 建立树; 叶节点没有“ 节点” 键
得到 leaf 节点( 树) # # 键 Error: “ 节点 ”□ 预期行为
get leaf nodes'应安全地处理没有nodes'密钥的节点,并作为叶节点返回。
□提议修补
用`.get()'取代直接密钥访问:
def get leaf nodes(结构):
如果存在( 结构, dict) :
如果没有结构的话. get('nodes'):# # # # # # 安全: 如果缺少密钥, 返回无( falsy)
结构 节点=复制.deepcopy(结构)
结构 node. pop( “ nodes' , 无)
返回 [结构 节点]
其他情况:
叶 节点= []
用于列表中的密钥( 结构. keys () ):
如果密钥中的“ 节点 ” :
叶子 节点.extend (get leaf 节点(结构[key])).
返回叶子 节点这是一个一行固定,符合“节点”是如何在编码库其他地方访问的(例如,format stitution'、is leaf node'、print tree'全部使用.get('nodes')')。
-- -- . . .
如果维护者愿意的话,我想努力解决这个问题。 很高兴提交公关证明.
内容来源: VectifyAI/PageIndex