在Python中加速合并多个XML文件

2024-09-30 08:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用xsl文件合并多个xml文件。文件数量大约为100个,每个文件有4000个节点。示例xml和xsl可在SO question中找到

我的xmlmerge.py具体如下:

import lxml.etree as ET
import argparse
import os
ap = argparse.ArgumentParser()
ap.add_argument("-x", "--xmlreffile", required=True, help="Path to list of xmls")
ap.add_argument("-s", "--xslfile", required=True, help="Path to the xslfile")
args = vars(ap.parse_args())    
dom = ET.parse(args["xmlreffile"])
xslt = ET.parse(args["xslfile"])
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))   

我正在将python的输出写入xml文件…因此运行python脚本的代码如下:

^{pr2}$

对于100个文件,当我在控制台上打印输出时,如果我尝试将相同的输出保存在xml文件中,则大约需要120分钟

^{3}$

这大约需要3天,但合并还没有结束。我不确定机器是否挂起,因此尝试在另一台机器上只使用8个文件,这花了4个多小时,但合并仍然没有完成。我不知道为什么写文件时要花这么多时间,而在控制台上打印时却不用。有人能引导我吗?在

我使用的是Ubuntu14.04,Python2.7。在


Tags: 文件importaddtrueparserequiredargparseargs
1条回答
网友
1楼 · 发布于 2024-09-30 08:34:45

为什么不制作一个多处理版本的脚本呢。有几种方法你可以做到,但据我所知,这里是我会做的

list = open("listofxmls.xml","r")# assuming this gives you a list of files (adapt if necessary)

yourFunction(xml):
    steps 
    of your
    parse funct
    return(ET.tostring(newdom, pretty_print=True))

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4) # number of threads (adapt depending on the task and your CPU)
mergedXML = pool.map(yourFunction,list) # execute the function in parallel
pool.close()
pool.join()

然后,根据需要保存mergedXML。在

希望它能帮助你,或者至少能引导你朝着正确的方向前进

相关问题 更多 >

    热门问题