代码之家  ›  专栏  ›  技术社区  ›  luc

如何知道文件在python中的编码?[副本]

  •  23
  • luc  · 技术社区  · 16 年前

    这个问题已经有了答案:

    有人知道如何用python编码文件吗?我知道您可以使用codecs模块打开具有特定编码的文件,但您必须提前知道。

    import codecs
    f = codecs.open("file.txt", "r", "utf-8")
    

    有没有一种自动检测文件使用哪种编码的方法?

    提前谢谢

    编辑: 感谢大家非常有趣的回答。您也可能对 http://whatismyencoding.com/ 这是基于chardet的(更多的站点是由瓶子python框架提供支持)

    5 回复  |  直到 9 年前
        1
  •  20
  •   Guillaume Jacquenot mbernasocchi    11 年前

    不幸的是,无法通过查看文件本身来确定文件的编码。这是一个通用问题,不局限于Python或任何特定的文件系统。

    如果您正在读取一个XML文件,文件中的第一行 可以 给你一个编码是什么的提示。

    否则,您将不得不使用一些基于启发式的方法,如 chardet (其他答案中给出的解决方案之一)试图通过检查文件中原始字节格式的数据来猜测编码。如果您使用的是Windows,我相信Windows API还公开了一些方法,尝试根据文件中的数据猜测编码。

        2
  •  9
  •   0 _ Edward Ned Harvey    10 年前

    您可以使用物料清单( http://en.wikipedia.org/wiki/Byte_order_mark )要检测编码,或尝试此库:

    https://github.com/chardet/chardet

        3
  •  4
  •   guettli    14 年前

    下面是一个小片段,帮助您猜测编码。它在Latin1和utf8之间的猜测相当好。它将字节字符串转换为Unicode字符串。

    # Attention: Order of encoding_guess_list is import. Example: "latin1" always succeeds.
    encoding_guess_list=['utf8', 'latin1']
    def try_unicode(string, errors='strict'):
        if isinstance(string, unicode):
            return string
        assert isinstance(string, str), repr(string)
        for enc in encoding_guess_list:
            try:
                return string.decode(enc, errors)
            except UnicodeError, exc:
                continue
        raise UnicodeError('Failed to convert %r' % string)
    def test_try_unicode():
        for start, should in [
            ('\xfc', u'ü'),
            ('\xc3\xbc', u'ü'),
            ('\xbb', u'\xbb'), # postgres/psycopg2 latin1: RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
            ]:
            result=try_unicode(start, errors='strict')
            if not result==should:
                raise Exception(u'Error: start=%r should=%r result=%r' % (
                        start, should, result))
    
        4
  •  3
  •   Guillaume Jacquenot mbernasocchi    11 年前

    Unicode Dammit Beautiful Soup ,它使用 chardet 但是增加了一些额外的功能。

    它试图从XML或HTML文件内部读取编码。然后它尝试在文件的开头查找一个BOM或类似的东西。如果不能做到这一点,它就利用 查德特 .

        5
  •  1
  •   Vladimir Grebenschikov    9 年前
    #!/usr/bin/python
    
    """
    Line by line detecting encoding if input and then convert it into UTF-8
    Suitable for look at logs with mixed encoding (i.e. from mail systems)
    
    """
    
    import sys
    import chardet
    
    while 1:
            l = sys.stdin.readline()
            e = chardet.detect(l)
    
            u = None
            try:
                    if e['confidence'] > 0.3:
                            u = unicode(l, e['encoding'])
            except:
                    pass
    
            if u:
                    print u,
            else:
                    print l,