Python遍历Azure Document Intelligence嵌套Sections列表并扁平化输出
非递归方式扁平化Azure Document Intelligence的Sections
代码实现
def flatten_sections(sections): result = [] # 栈元素:(当前section字典, 当前section的路径) stack = [] # 初始化栈,加入所有根级sections for idx, section in enumerate(sections): stack.append( (section, f"/sections/{idx}") ) while stack: current_section, current_path = stack.pop() # 处理当前section下的paragraphs if "paragraphs" in current_section: for p_idx, _ in enumerate(current_section["paragraphs"]): para_path = f"{current_path}/paragraphs/{p_idx}" result.append(para_path) # 处理当前section下的tables if "tables" in current_section: for t_idx, _ in enumerate(current_section["tables"]): table_path = f"{current_path}/tables/{t_idx}" result.append(table_path) # 处理嵌套的子sections,逆序压栈保证遍历顺序和原结构一致 if "sections" in current_section: # 逆序遍历,因为栈是后进先出,这样弹出时顺序和原列表一致 for s_idx in reversed(range(len(current_section["sections"]))): sub_section = current_section["sections"][s_idx] sub_path = f"{current_path}/sections/{s_idx}" stack.append( (sub_section, sub_path) ) return result
代码说明
- 栈初始化:将每个根级section与对应路径(
/sections/索引)加入栈,作为遍历起点。 - 循环处理栈元素:每次从栈顶弹出一个section及其路径,依次处理三类内容:
- Paragraphs/Tables处理:若当前section包含
paragraphs或tables字段,遍历每个元素,拼接完整路径后加入结果列表。 - 嵌套Sections处理:若存在子sections,逆序压入栈(利用栈后进先出的特性,保证弹出时顺序与原列表一致),同时拼接子section的路径。
- Paragraphs/Tables处理:若当前section包含
- 结果返回:最终得到所有paragraph和table的完整路径列表,可直接用于后续关联提取内容。
使用示例
假设输入的sections简化结构如下:
sections = [ { "paragraphs": [{"content": "段落1"}, {"content": "段落2"}], "sections": [ { "paragraphs": [{"content": "嵌套段落1"}], "tables": [{"cells": []}] } ] }, { "tables": [{"cells": []}] } ]
调用flatten_sections(sections)会得到:
[ "/sections/0/paragraphs/0", "/sections/0/paragraphs/1", "/sections/0/sections/0/paragraphs/0", "/sections/0/sections/0/tables/0", "/sections/1/tables/0" ]
内容的提问来源于stack exchange,提问作者Shubham R
相关产品推荐
相关产品推荐

