Unescape _xHHHH_使用Python的XML转义序列 [英] Unescape _xHHHH_ XML escape sequences using Python

查看:85
本文介绍了Unescape _xHHHH_使用Python的XML转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python 2.x [不可协商]来读取允许许多元素的内容包含不具有有效XML字符的XML文档[通过其他人创建],使用 _xHHHH _ 约定例如ASCII BEL aka U + 0007由7个字符的序列 u_x0007 _表示。允许在文档中表示任何旧字符的功能和转义方式都是可协商的。我正在使用cElementTree或lxml [semi-negotiable]解析文档。

I'm using Python 2.x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the _xHHHH_ convention e.g. ASCII BEL aka U+0007 is represented by the 7-character sequence u"_x0007_". Neither the functionality that allows representation of any old character in the document nor the manner of escaping is negotiable. I'm parsing the documents using cElementTree or lxml [semi-negotiable].

这是我尽可能高效地解析解析器输出的最好方法:

Here is my best attempt at unescapeing the parser output as efficiently as possible:

import re
def unescape(s,
    subber=re.compile(r'_x[0-9A-Fa-f]{4,4}_').sub,
    repl=lambda mobj: unichr(int(mobj.group(0)[2:6], 16)),
    ):
    if "_" in s:
         return subber(repl, s)
    return s

通过在典型文本中观察到非常低的_频率,并且通过在可能的情况下避免正则表达式装置,提高了一倍以上的速度,上述是偏爱的。

The above is biassed by observing a very low frequency of "_" in typical text and a better-than-doubling of speed by avoiding the regex apparatus where possible.

问题:有什么更好的想法吗?

The question: Any better ideas out there?

推荐答案

你也可以检查'_ x'而不仅仅是 _ ,这并不重要,但确实两个字符序列比单个下划线更罕见。除了这样的细节,你似乎正在做出最好的一个坏的情况!

You might as well check for '_x' rather than just _, that won't matter much but surely the two-character sequence's even rarer than the single underscore. Apart from such details, you do seem to be making the best of a bad situation!

这篇关于Unescape _xHHHH_使用Python的XML转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆