Jupyter Notebook层级控制台输出按符号分多列导出至Excel的实现方法
层级打印内容导出为Excel三列结构的实现方法
你需要先对myList中存储的层级字符串做符号与层级解析,分别跟踪当前的一级(*对应)、二级(+对应)、三级(-对应)内容,逐行生成三列结构的数据后再导出Excel即可实现需求。
完整实现代码如下:
import pandas as pd # 初始化各层级当前值变量 current_l1 = "" current_l2 = "" current_l3 = "" parsed_rows = [] # 遍历所有待输出内容做层级解析 for content in myList: # 去除前置制表符、空格,判断内容所属层级 stripped_content = content.lstrip() if stripped_content.startswith("*"): # 一级内容,更新一级值,清空下级当前值 current_l1 = stripped_content.split("*", 1)[1].strip() current_l2 = "" current_l3 = "" elif stripped_content.startswith("+"): # 二级内容,更新二级值,清空三级当前值 current_l2 = stripped_content.split("+", 1)[1].strip() current_l3 = "" elif stripped_content.startswith("-"): # 三级内容,更新三级值 current_l3 = stripped_content.split("-", 1)[1].strip() # 存入当前行的三列数据 parsed_rows.append({ "星号内容列": current_l1, "加号内容列": current_l2, "减号内容列": current_l3 }) # 导出到Excel df = pd.DataFrame(parsed_rows) with pd.ExcelWriter("Result.xlsx", engine="xlsxwriter") as writer: df.to_excel(writer, sheet_name="Sheet1", index=False)
导出的Excel会自动生成三列,上级层级的内容会自动填充到所有下属行中,完全匹配你需要的层级对应效果。
内容的提问来源于stack exchange,提问作者YasserKhalil
相关产品推荐
相关产品推荐

