【问题标题】:Python - Decode UTF-16 file with BOMPython - 使用 BOM 解码 UTF-16 文件
【发布时间】:2014-04-22 22:23:30
【问题描述】:

我有一个带有BOMUTF-16 LE 文件。我想将此文件翻转为不带 BOM 的 UTF-8,以便我可以使用 Python 对其进行解析。

我使用的常用代码没有解决问题,它返回未知字符而不是实际文件内容。

f = open('dbo.chrRaces.Table.sql').read()
f = str(f).decode('utf-16le', errors='ignore').encode('utf8')
print f

解码这个文件的正确方法是什么,以便我可以用f.readlines() 解析它?

【问题讨论】:

  • 如果这是在 Windows 上,请尝试以二进制模式打开文件,看看是否有帮助。

标签: python file encoding utf-8 utf-16


【解决方案1】:

首先,你应该以二进制模式阅读,否则事情会变得混乱。

然后,检查并删除 BOM,因为它是文件的一部分,而不是实际文本的一部分。

import codecs
encoded_text = open('dbo.chrRaces.Table.sql', 'rb').read()    #you should read in binary mode to get the BOM correctly
bom = codecs.BOM_UTF16_LE                                      #print dir(codecs) for other encodings
assert encoded_text.startswith(bom)                           #make sure the encoding is what you expect, otherwise you'll get wrong data
encoded_text = encoded_text[len(bom):]                         #strip away the BOM
decoded_text = encoded_text.decode('utf-16le')                 #decode to unicode

在完成所有解析/处理之前,请勿编码(至 utf-8 或其他方式)。您应该使用 unicode 字符串来完成所有这些操作。

此外,decode 上的 errors='ignore' 可能不是一个好主意。考虑一下更糟糕的情况:让您的程序告诉您有问题并停止,还是返回错误数据?

【讨论】:

    【解决方案2】:

    这适用于 Python 3:

    f  = open('test_utf16.txt', mode='r', encoding='utf-16').read()
    print(f)
    

    【讨论】:

    • 如果只将编码设置为utf-16,则不必手动消除BOM。
    • 经过编辑使其成为utf-16,它似乎没有记录在案,但utf-16 的编码似乎确实会自动处理BOM。如果您使用utf-16le,它仍然有效,但BOM 仍然存在,您可以使用字符串函数和codecs.BOM_UTF16_BE 自行删除
    猜你喜欢
    • 2015-07-14
    • 2020-01-15
    • 1970-01-01
    • 2020-08-02
    • 2013-08-16
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多