2016-06-28 37 views
2

如何获得UnicodeDecodeError发生位置? 我发现材料超过here并试图在下面实施。但我只是得到一个错误NameError: name 'err' is not defined如何获得UnicodeDecodeError发生的位置?

我已经在互联网上搜索了已经在这里和StackOverflow,但找不到任何提示如何使用它。在python文档中,它说这个特殊的异常有start属性,所以它必须是可能的。

谢谢。

data = buffer + data 
    try: 
     data = data.decode("utf-8") 
    except UnicodeDecodeError: 
     #identify where did the error occure? 
     #chunk that piece off -> copy troubled piece into buffer and 
     #decode the good one -> then go back, receive the next chunk of 
     #data and concatenate it to the buffer. 

     buffer = err.data[err.start:] 
     data = data[0:err.start] 
     data = data.decode("utf-8") 
+0

投票方式关闭如琐碎'因为答案是一个重要的语法细节。可能仍然有用,供将来参考。 –

回答

4

该信息存储在例外本身中。你可以用as关键字异常对象,并使用start属性:

while True: 
    try: 
     data = data.decode("utf-8") 
    except UnicodeDecodeError as e: 
     data = data[:e.start] + data[e.end:] 
    else: 
     break 
+0

那很简单。非常感谢:) –

+0

在文档中他们说:“例如,err.object [err.start:err.end]给出了编解码器失败的特定无效输入。”这是什么:err.object [err.start:err.end]实际上是什么意思?它与e.start不一样,甚至不是很接近。 –

+1

@Cooper:很好!我应该编辑我的答案。其实它很接近。这是[切片](https://docs.python.org/3/reference/expressions.html#slicings)。它意味着把所有位置在'err.start'和'err.end'位置之间。这包括'err.start',但不包括'err.end'。在大多数情况下,结束只是开始后的一个字符,所以我的解决方案将工作。但是,我认为有些情况下,'err.end'不止一个更高。 – zondo

0

如果你只是想忽略错误和解码的休息,你可以这样做:

data = data.decode("utf-8", errors='ignore') 
+0

谢谢,我会牢记在心:) –