【问题标题】:How to detect string byte encoding?如何检测字符串字节编码?
【发布时间】:2013-04-01 20:23:29
【问题描述】:

os.listdir() 读取了大约 1000 个文件名,其中一些以 UTF8 编码,一些是 CP1252。

我想将它们全部解码为 Unicode,以便在我的脚本中进行进一步处理。有没有办法让源编码正确解码成 Unicode?​​p>

例子:

for item in os.listdir(rootPath):

    #Convert to Unicode
    if isinstance(item, str):
        item = item.decode('cp1252')  # or item = item.decode('utf-8')
    print item

【问题讨论】:

    标签: python string unicode encoding byte


    【解决方案1】:

    使用 chardet 库。超级简单

    import chardet
    
    the_encoding = chardet.detect('your string')['encoding']
    

    就是这样!

    在 python3 中你需要提供类型 bytes 或 bytearray 所以:

    import chardet
    the_encoding = chardet.detect(b'your string')['encoding']
    

    【讨论】:

    • 在我看来它不起作用。我创建了字符串变量并将其编码为 utf-8。 chardet 返回 TIS-620 编码。
    • 我发现 cchardet 似乎是此库或类似库的当前名称...; chardet 找不到。
    • 这里有点困惑。似乎不可能提供 str 类作为参数。只有 b'your string' 对我有用,或者直接提供一个字节变量。
    • 这个答案对我来说的问题是,一些 cp1252/latin1 字符可以被解释为技术上有效的 utf8 - 这导致 ê 类型字符应该是 êchardet 似乎先尝试 utf8,结果是这样。可能有办法告诉它使用哪个顺序,但lucemia's answer 对我来说效果更好。
    • 在 Python 3 中:TypeError: Expected object of type bytes or bytearray, got: <class 'str'>
    【解决方案2】:

    如果您的文件在cp1252utf-8 中,那么有一个简单的方法。

    import logging
    def force_decode(string, codecs=['utf8', 'cp1252']):
        for i in codecs:
            try:
                return string.decode(i)
            except UnicodeDecodeError:
                pass
    
        logging.warn("cannot decode url %s" % ([string]))
    
    for item in os.listdir(rootPath):
        #Convert to Unicode
        if isinstance(item, str):
            item = force_decode(item)
        print item
    

    否则,有一个字符集检测库。

    Python - detect charset and convert to utf-8

    https://pypi.python.org/pypi/chardet

    【讨论】:

      【解决方案3】:

      你也可以使用json包来检测编码。

      import json
      
      json.detect_encoding(b"Hello")
      

      【讨论】:

        猜你喜欢
        • 2012-12-20
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        • 2020-05-22
        • 1970-01-01
        相关资源
        最近更新 更多