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

问题描述 投票:0回答:1

我正在使用xsl文件来合并多个xml文件。文件数约为100,每个文件有4000个节点。此SO question中提供了示例xml和xsl

我的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的输出写入xmlfile ...所以我运行python脚本的代码如下:

python xmlmerge.py --xmlreffile ~/Documents/listofxmls.xml --xslfile ~/Documents/xslfile.xsl

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

python xmlmerge.py --xmlreffile ~/Documents/listofxmls.xml --xslfile ~/Documents/xslfile.xsl >> ~/Documents/mergedxml.xml

这需要大约3天,但合并尚未结束。我不确定机器是否挂起,因此在另一台机器上仅使用8个文件进行了尝试,并且耗时超过4小时,但合并仍未完成。我不知道为什么写入文件需要花费很多时间,而不是在打印到控制台时。有人可以指导我吗?

我使用的是Ubuntu 14.04,python 2.7。

python linux bash xslt lxml
1个回答
0
投票

为什么不制作脚本的多处理版本。有几种方法可以做到,但据我所知,这就是我要做的

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。

希望它有助于或者至少引导你走向正确的方向

© www.soinside.com 2019 - 2024. All rights reserved.