编码解码Python

ann*_*man 1 python encoding decoding

我在文本文件中有文本" confrères ",编码格式为"ISO-8859-2".我想在python中以"UTF-8"编码这个值.

我在python(2.7)中使用以下代码来转换它,但转换后的值[" confrčres "]与原始值[ " confrères "]不同.

# -*- coding: utf-8 -*-

import chardet
import codecs

a1=codecs.open('.../test.txt', 'r')

a=a1.read()

b = a.decode(chardet.detect(a)['encoding']).encode('utf8')

a1=codecs.open('.../test_out.txt', 'w').write(b)
Run Code Online (Sandbox Code Playgroud)

任何想法如何获得实际值,但在输出文件中以UTF8编码格式.

谢谢

Mar*_*ers 5

如果您知道使用的编解码器,请不要使用chardet.字符检测绝不是万无一失的,图书馆猜错了你的文件.

请注意,ISO-8859-2是错误的编解码器,因为该编解码器甚至无法对字母进行编码è.您可以使用ISO-8859-1(Latin-1)或Windows代码页1252数据; è在8859-1和cp1252编码为0xE8,而8859-2中的0xE8为?:

>>> print u'confr?res'.encode('iso-8859-2').decode('iso-8859-1')
confrères
Run Code Online (Sandbox Code Playgroud)

可能是8859-2猜测chardet了吗?

您可以使用该io来动态处理解码和编码; 它是处理Python 3中所有I/O的相同代码库,并且问题少于codecs:

from shutil import copyfileobj

with open('test.txt', 'r', encoding='iso-8859-1') as inf:
    with open('test_out.txt', 'w', encoding='utf8') as outf:
        copyfileobj(inf, outf)
Run Code Online (Sandbox Code Playgroud)

我曾经shutil.copyfileobj()处理过数据的复制.