我可以在python中绕过UnicodeDecodeError吗?

big*_*801 2 python xml django parsing illegal-characters

我有一个解析xml文件的python脚本,并返回以下错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 614617: character maps to <undefined>

我很确定错误正在发生,因为我试图解析的xml文档中有一些非法字符,但是我没有权限直接修复我正在阅读的这个特定的xml文件.

我能够拥有它,以便这些字符不会绊倒我的脚本并允许它保持解析而不会出错吗?

这是脚本的一部分,就是读取xml并解码它:

def ReadXML(self, path):
    self.logger.info("Reading XML from %s" % path)
    codec = "Windows-1252"
    xmlReader = open(path, "r")
    return xmlReader.read().decode(codec)
Run Code Online (Sandbox Code Playgroud)

cjm*_*cjm 7

调用时decode(),可以传递可选errors参数.默认情况下,它设置为strict(如果找到无法解析的内容,则会引发错误),但您也可以将其设置为replace(用有问题的字符替换\ufffd)或ignore(只是将有问题的字符排除在外).

所以它会是:

return xmlReader.read().decode(codec, errors='ignore')
Run Code Online (Sandbox Code Playgroud)

或者你选择的任何级别.

更多信息可以在Python Unicode HOWTO中找到.

  • @ bigmike7801:如果你看一下[文档](http://docs.python.org/library/stdtypes.html#str.decode),你会看到第二个位置参数是`errors`,所以是的,它是相同.总是鼓励阅读文档. (2认同)