python - 加快读取 xml 文件的速度

标签 python xml performance

我有一份专利文档,它是一个文本文档中的 xml 文件的串联字符串。我希望将其分成单独的文档,每个文档都是一个 xml 文件。我的代码可以工作,但我需要加快速度。我的代码是这样的:

import time

count = 0

filestr = ''

line = 'x'

start_time = time.time()
with open('C:/Users/RNCZF01/Documents/Cameron-Fen/Economics-Projects/Patent-project/similarity/Patents/ipg121225.xml') as txtfile:
while line:        
    line = txtfile.readline()
    if '<?xml version="1.0" encoding="UTF-8"?>' in line:
        filestr = str(count) + '.xml'
        count += 1

    with open('C:/Users/RNCZF01/Documents/Cameron-Fen/Economics-Projects/Patent-project/similarity/Patents/2012-12-25/' + filestr, 'ab') as textfile:
        textfile.write(line)
        textfile.write('\n')

print("--- %s seconds ---" % (time.time() - start_time))

我能想到的加快速度的一项优化是 if 语句。它检查该行是否包含 xml header : <?xml version="1.0" encoding="UTF-8"?> 。如果我可以检查该行是否为 <?xml version="1.0" encoding="UTF-8"?>,可能会快得多。而不是仅仅包含它。但是当我写 if line == '<?xml version="1.0" encoding="UTF-8"?>':它不接电话。我需要添加 \n最后还是什么?您还可以想到其他优化来加快此过程吗?谢谢,

卡梅伦

最佳答案

您可能想要加载整个文件内容并执行 python 正则表达式模式匹配器,而不是检查每一行。这样,您只需调用方法 findall() 即可减少检查和获取所有匹配项的步骤。

这是文档链接 - https://docs.python.org/3/howto/regex.html

关于python - 加快读取 xml 文件的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532805/

相关文章:

c# - 任何等效于 C# 的 "extended"?

python - Pip 默认行为与 virtualenv 冲突?

android - 设置 inputType textFilter 和 textPassword 停止显示为密码点而不是密码点本身

java - antlr4 在多核 CPU 上的性能

android - 剪辑按钮不接收触摸输入

android - XmlPullParser - 意外 token (android)

linux - Linux VM 上的 Docker,性能如何?

python - urllib2.urlopen : "Name or service not known" persists when starting script without internet connection

python - 快速 Tkinter 格式化问题

python - 用字典中的值交换键的改进?