【问题标题】:Python: how to convert from Windows 1251 to Unicode?Python:如何从 Windows 1251 转换为 Unicode?
【发布时间】:2011-04-27 15:55:02
【问题描述】:

我正在尝试使用 Python 将文件内容从 Windows-1251 (Cyrillic) 转换为 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()

我该怎么做?

谢谢

【问题讨论】:

  • Unicode是什么编码?
  • @Gumbo,从代码判断输出应该是 UTF-8。

标签: python unicode encoding


【解决方案1】:
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

这是你打算做的吗?

【讨论】:

  • 我觉得你很亲近!我设法从 XML 读取数据,但是当我将其写入文件时,我得到奇怪的字符而不是西里尔字符。
  • 是的!我知道了!我改用cp1252。非常感谢
  • @Alex,很高兴知道您的代码可以正常工作。你可能想看看evanjones.ca/python-utf8.html,那里有一些很好的提示。
【解决方案2】:

这只是一个猜测,因为您没有具体说明“不起作用”是什么意思。

如果文件生成正确,但似乎包含垃圾字符,则您正在查看它的应用程序可能无法识别它包含 UTF-8。您需要在文件开头添加一个 BOM - 3 个字节 0xEF,0xBB,0xBF(未编码)。

【讨论】:

    【解决方案3】:

    如果您使用codecs 模块打开文件,它会在您读取文件时为您转换为Unicode。例如:

    import codecs
    f = codecs.open('input.txt', encoding='cp1251')
    assert isinstance(f.read(), unicode)
    

    这仅在您使用 Python 处理文件数据时才有意义。如果您尝试在文件系统上将文件从一种编码转换为另一种编码(这是您发布的脚本尝试执行的操作),您必须指定实际编码,因为您不能在 "统一码”。

    【讨论】:

    • 我仍然收到错误 UnicodeEncodeError: 'charmap' codec can't encode characters in position: character maps to
    • 您使用的实际代码是什么?哪一行触发了这个异常?
    • @Will McCutchen - 你应该使用'rb' 作为模式。将其覆盖到 'r' 几乎不是您想要做的。
    • @Alex:你确定它被编码为 CP1251 而不是 ISO-8859-5 或其他代码页吗?尝试使用encodings.cp1251.StreamReader 读取输入。
    • @D.Shawley,编解码器模块总是以二进制模式打开文件。
    猜你喜欢
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2011-02-17
    • 2010-09-30
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多