我已经制作了一个模块来检测文件的编码。我希望能够将文件路径和编码作为类的输入,并始终能够在处理文件内容时返回“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的接口。
已经有图书馆可以这样做了吗?
最佳答案
基于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')