问题:


我有包含感兴趣数据的大(> 2GB)文本文件
在超过90%的情况下,我可以假定此数据的格式设置为UTF-8或西欧
在极少数情况下,我还有其他奇怪的编码


我试过的

我从使用chardet开始,但是该应用程序在性能上受到了很大的影响,因为它在检测到编码之前将整个文件加载到RAM中。然后,我想也许我应该只是将一些代表性数据读入chardet的detect方法中,但随后我意识到我不会丢失任何可能引起问题的随机字符(例如'®'字符会在文本文件中引起问题否则将解码为UTF-8就可以了)。为了避免遭受这种打击,除非我必须这样做,我选择了以下路线:

def get_file_handle(self):
    """
    Default encoding is UTF-8. If that fails, try Western European (Windows-1252), else use chardet to detect
    :return: file handle (f)
    """
    try:
        with codecs.open(self.current_file, mode='rb', encoding='utf-8') as f:
            return f
    except UnicodeDecodeError:
        try:
            with codecs.open(self.current_file, mode='rb', encoding='cp1252') as f:
                return f
        except UnicodeDecodeError:
            # read raw data and detect encoding via chardet (last resort)
            raw_data = open(self.current_file, 'r').read()
            result = chardet.detect(raw_data)
            char_enc = result['encoding']
            with codecs.open(self.current_file, mode='rb', encoding=char_enc) as f:
                return f


在这种情况下,在极少数情况下,它会遇到第三个/最里面的异常,它仍会将整个文件读入RAM。简单地读取一些随机的代表数据可能会丢失文本文档中令人反感的字符。这是我想做的:


当我收到UnicodeDecodeError时,回溯的最后一行是:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xae in position 2867043: invalid start byte
我想获取字节偏移量(0xae),然后从文件中获取1.000个字符,并将其馈送到chardet进行检测,从而包括令人讨厌的字符以及用于编码预测的其他数据。


我已经知道如何分块读取数据(但也可以随意添加),主要是我对如何从回溯中获取字节偏移感兴趣。

最佳答案

这个怎么样:

except UnicodeDecodeError as e:
    # read raw data and detect encoding via chardet (last resort)
    with open(self.current_file, 'r') as f:
        f.seek(e.start - 1000)
        raw_data = f.read(2000)
        result = chardet.detect(raw_data)
        ...

关于python - 从Python UnicodeDecodeError异常获取错误的字节偏移,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33111078/

10-12 22:45
查看更多