Python:如何将 Windows 1251 转换为 Unicode?

标签 python unicode encoding

我正在尝试使用 Python 将文件内容从 Windows-1251(西里尔文)转换为 Unicode。我找到了这个功能,但是它不起作用。

#!/usr/bin/env python

import os
import sys
import shutil

def convert_to_utf8(filename):
# gather the encodings you think that the file may be
# encoded inside a tuple
encodings = ('windows-1253', 'iso-8859-7', 'macgreek')

# try to open the file and exit if some IOError occurs
try:
    f = open(filename, 'r').read()
except Exception:
    sys.exit(1)

# now start iterating in our encodings tuple and try to
# decode the file
for enc in encodings:
    try:
        # try to decode the file with the first encoding
        # from the tuple.
        # if it succeeds then it will reach break, so we
        # will be out of the loop (something we want on
        # success).
        # the data variable will hold our decoded text
        data = f.decode(enc)
        break
    except Exception:
        # if the first encoding fail, then with the continue
        # keyword will start again with the second encoding
        # from the tuple an so on.... until it succeeds.
        # if for some reason it reaches the last encoding of
        # our tuple without success, then exit the program.
        if enc == encodings[-1]:
            sys.exit(1)
        continue

# now get the absolute path of our filename and append .bak
# to the end of it (for our backup file)
fpath = os.path.abspath(filename)
newfilename = fpath + '.bak'
# and make our backup file with shutil
shutil.copy(filename, newfilename)

# and at last convert it to utf-8
f = open(filename, 'w')
try:
    f.write(data.encode('utf-8'))
except Exception, e:
    print e
finally:
    f.close()

我该怎么做?

谢谢

最佳答案

import codecs

f = codecs.open(filename, 'r', 'cp1251')
u = f.read()   # now the contents have been transformed to a Unicode string
out = codecs.open(output, 'w', 'utf-8')
out.write(u)   # and now the contents have been output as UTF-8

这是你打算做的吗?

关于Python:如何将 Windows 1251 转换为 Unicode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5806980/

相关文章:

python - 如何将视频转换为 numpy 数组?

Python:解析大型 json 文件

python - 在 Numpy 中应用不使用 for 循环的非平凡矩阵计算

python - 欧拉计划 #19 - 计算星期天问题

java - Java 的 String.getBytes ("ISO-8859-1") 是否返回字符串中每个 2 字节字符的第一个字节?

c# - razor 如何将字节 [8] 转换为字符串?

string - 如何删除不可打印的字符

Python:替换 Unicode 中的不间断空格

python - Unicode解码错误: 'utf-8' codec can't decode byte 0x80

ruby-on-rails - 使用 Ruby/Rails 进行 base 64 URL 解码?