【问题标题】:How can I implement a file like class that always returns in UTF-8 encoding irrespective of file encoding?无论文件编码如何,如何实现始终以 UTF-8 编码返回的类文件?
【发布时间】:2017-05-19 23:59:42
【问题描述】:

我制作了一个检测文件编码的模块。我希望能够将文件路径和编码作为类的输入,并且在处理文件内容时始终能够返回“utf-8”。

比如这样的

handler = UnicodeWrapper(file_path, encoding='ISO-8859-2')

for line in handler:
   # need the line to be encoded in utf-8
   process(line)

我不明白为什么还有一百万种编码。但是我想写一个总是返回unicode的接口。

是否已经有图书馆可以做到这一点?

【问题讨论】:

  • 不完全是,但 Codecs 模块为您提供了允许您将文件读入 unicode 字符串的包装器,这或多或少是 Python3 open 也直接允许的。

标签: python python-2.7 encoding utf-8


【解决方案1】:

基于this answer,我认为以下可能适合您的需求:

import io

class UnicodeWrapper(object):
    def __init__(self, filename):
        self._filename = filename

    def __iter__(self):
        with io.open(self._filename,'r', encoding='utf8') as f:
            return iter(f.readlines())

if __name__ == '__main__':
    filename = r'...'

    handler = UnicodeWrapper(filename)

    for line in handler:
       print(line)

编辑

在 Python 2 中,您可以断言每一行都使用 UTF-8 编码,如下所示:

if __name__ == '__main__':
    filename = r'...'

    handler = UnicodeWrapper(filename)

    for line in handler:
        try:
            line.decode('utf-8')
            # process(line)
        except UnicodeDecodeError:
            print('Not encoded in UTF-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多