使用Python将MATSIM population复杂XML文件转换为指定字段CSV
MATSIM population XML转CSV Python实现方案
核心思路
- 直接使用Python标准库
xml.etree.ElementTree解析XML文件,无需额外安装第三方依赖,完全兼容population_v6.dtd规范 - 遍历所有
person节点提取人员ID,仅保留标记为selected="yes"的生效计划 - 按顺序配对活动节点(
activity)和后续出行段节点(leg),将对应属性写入CSV - 采用标准库
csv处理输出,自动处理特殊字符、避免编码错误
可直接运行的代码
import xml.etree.ElementTree as ET import csv # 替换为你的实际文件路径 XML_INPUT_PATH = "population.xml" CSV_OUTPUT_PATH = "population_output.csv" # CSV表头可根据实际提取需求增删字段 CSV_FIELDS = [ "person_id", "activity_type", "x", "y", "end_time", "subsequent_leg_mode" ] def convert_matsim_xml_to_csv(): # 解析XML文件 tree = ET.parse(XML_INPUT_PATH) root = tree.getroot() with open(CSV_OUTPUT_PATH, "w", encoding="utf-8", newline="") as csv_file: writer = csv.DictWriter(csv_file, fieldnames=CSV_FIELDS) writer.writeheader() # 遍历所有人员 for person in root.findall("person"): pid = person.get("id") # 取当前生效的选中计划 selected_plan = person.find("./plan[@selected='yes']") if not selected_plan: continue plan_nodes = list(selected_plan) # 配对活动与后续出行 for idx, node in enumerate(plan_nodes): if node.tag != "activity": continue # 提取活动属性 row_data = { "person_id": pid, "activity_type": node.get("type"), "x": node.get("x"), "y": node.get("y"), "end_time": node.get("end_time"), "subsequent_leg_mode": "" } # 提取下一个节点的出行模式,最后一个活动无后续出行则留空 if idx + 1 < len(plan_nodes) and plan_nodes[idx+1].tag == "leg": row_data["subsequent_leg_mode"] = plan_nodes[idx+1].get("mode") writer.writerow(row_data) if __name__ == "__main__": convert_matsim_xml_to_csv() print(f"转换完成,输出文件路径:{CSV_OUTPUT_PATH}")
自定义调整说明
- 若需要单独导出出行段数据,可新增逻辑遍历
leg节点,关联前后活动的属性 - 若处理超大XML文件(百兆以上),可改用
ET.iterparse迭代解析,避免一次性加载全量文件占用过高内存 - 若需要新增其他提取字段,直接在
row_data中补充对应属性提取逻辑即可,例如提取活动的start_time、计划的score属性等
内容的提问来源于stack exchange,提问作者Elham
相关产品推荐
相关产品推荐

