当前位置: 首页 > 面试题库 >

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

仉洲
2023-03-14
问题内容

我正在尝试使用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()

我怎样才能做到这一点?

谢谢


问题答案:
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

这是您打算做什么?



 类似资料:
  • 问题内容: 即 此代码 给我 : 2012-16-02 05:16:17 什么时候 返回: 2012-01-02 05:16:17.0 问题答案: 您应该改用日历:

  • 我有一个来自源代码的,根据规范,它应该是,但在类中没有看到任何方法将转换为。 最好的方法是什么?

  • 问题内容: 我有一堆坐标为UTM格式的文​​件。对于每个坐标,我都有东,北和区域。我需要将其转换为LatLng以与Google MapAPI一起使用,以在地图中显示信息。 我发现有一些在线计算器可以执行此操作,但是没有实际的代码或库。http://trac.osgeo.org/proj4js/是Javascript的投影库,但是在演示中,它不包含UTM投影。 我对整个GIS领域仍然很新鲜,所以我想

  • 问题内容: 我有一个要转换为CSV文件的JSON文件。如何使用Python执行此操作? 我试过了: 但是,它没有用。我正在使用Django,收到的错误是: 然后,我尝试了以下方法: 然后我得到错误: 样本json文件: 问题答案: 首先,你的JSON具有嵌套对象,因此通常无法直接将其转换为CSV。你需要将其更改为以下内容: 这是从中生成CSV的代码: 你将获得以下输出:

  • 问题内容: 我只想知道是否有一个程序可以像 JAXB for Java那样将XSD文件转换为Python类? 问题答案: generateDS:我认为这是我需要的好工具 编辑:实际上,generateDS做得很好!它使用所有方法(setter和getter,导出到XML,从XML导入)生成Python类。效果很好!

  • 问题内容: 我想在Golang中将int转换为hex。在strconv中,有一种将字符串转换为十六进制的方法。是否有类似的方法从int获取十六进制字符串? 问题答案: 由于hex是Integer文字,因此您可以使用,和或格式向fmt包询问该整数的字符串表示形式。参观游乐场 输出: