Unescape _xHHHH_ XML escape sequences using Python

冷暖自知 提交于 2019-12-10 18:57:29

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/1030522/unescape-xhhhh-xml-escape-sequences-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!