Andrey Vlasovskikh 接受的答案是对 OP 的最完整答案。但是这个主题出现在python escape xml 的最频繁搜索中,我想提供所讨论的三种解决方案的时间比较
在本文中,同时提供了我们选择部署的第四个选项,因为它提供了增强的性能。
这四个都依赖于原生 Python 数据处理或 Python 标准库。解决方案按性能从最慢到最快的顺序提供。
选项 1 - 正则表达式
此解决方案使用 python 正则表达式库。它产生最慢的性能:
import re
table = {
"<": "<",
">": ">",
"&": "&",
"'": "'",
'"': """,
}
pat = re.compile("({})".format("|".join(table)))
def xmlesc(txt):
return pat.sub(lambda match: table[match.group(0)], txt)
>>> %timeit xmlesc('<&>"\'')
1.48 µs ± 1.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
仅供参考:µs 是微秒的符号,即百万分之一秒。另一个实现的完成时间以纳秒 (ns) 为单位,即十亿分之一秒。
选项 2 -- xml.sax.saxutils
此解决方案使用 python xml.sax.saxutils 库。
from xml.sax.saxutils import escape
def xmlesc(txt):
return escape(txt, entities={"'": "'", '"': """})
>>> %timeit xmlesc('<&>"\'')
832 ns ± 4.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
选项 3 - str.replace
此解决方案使用字符串replace() 方法。在底层,它实现了与 python 的xml.sax.saxutils 类似的逻辑。 saxutils 代码有一个 for 循环,它会消耗一些性能,使这个版本稍微快一些。
def xmlesc(txt):
txt = txt.replace("&", "&")
txt = txt.replace("<", "<")
txt = txt.replace(">", ">")
txt = txt.replace('"', """)
txt = txt.replace("'", "'")
return txt
>>> %timeit xmlesc('<&>"\'')
503 ns ± 0.725 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
选项 4 - str.translate
这是最快的实现。它使用字符串translate() 方法。
table = str.maketrans({
"<": "<",
">": ">",
"&": "&",
"'": "'",
'"': """,
})
def xmlesc(txt):
return txt.translate(table)
>>> %timeit xmlesc('<&>"\'')
352 ns ± 0.177 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)