【问题标题】:Character detection in a text file in Python using the Universal Encoding Detector (chardet)使用通用编码检测器 (chardet) 在 Python 中的文本文件中检测字符
【发布时间】:2011-03-20 10:07:15
【问题描述】:

我正在尝试使用 Python 中的通用编码检测器 (chardet) 来检测文本文件 ('infile') 中最可能的字符编码,并将其用于进一步处理。

虽然 chardet 主要用于检测网页的字符编码,但我发现 example 用于单个文本文件。

但是,我不知道如何告诉脚本将最可能的字符编码设置为变量“charenc”(在整个脚本中多次使用)。

我的代码,基于上述示例和chardet自己的documentation的组合如下:

import chardet    
rawdata=open(infile,"r").read()
chardet.detect(rawdata)

字符检测是必要的,因为脚本继续运行以下(以及几个类似的用途):

inF=open(infile,"rb")
s=unicode(inF.read(),charenc)
inF.close()

任何帮助将不胜感激。

【问题讨论】:

    标签: python character-encoding


    【解决方案1】:

    chardet.detect() 返回一个字典,它提供编码作为与键 'encoding' 关联的值。所以你可以这样做:

    import chardet    
    rawdata = open(infile, 'rb').read()
    result = chardet.detect(rawdata)
    charenc = result['encoding']
    

    The chardet documentation 并没有明确说明文本字符串和/或字节字符串是否应该与模块一起使用,但有理由认为,如果您有文本字符串,则不需要对其运行字符检测,因此您可能应该传递字节字符串。因此,在对open() 的调用中使用了二进制模式标志(b)。但是chardet.detect() 也可能与文本字符串一起使用,具体取决于您使用的 Python 版本和库的版本,即如果您确实省略了b,您可能会发现它仍然有效,即使您在技术上正在做某事错了。

    【讨论】:

    • 谢谢!我以为这会很简单!
    • 正是我所需要的。出于好奇,有没有办法让它返回一个以上的结果,这样你就可以看到 3 个最高置信水平的猜测?
    • @Endophage 我不确定,我自己并没有真正使用它。
    • Python 3.6 在尝试打开 UTF-8 文件时抛出了 TypeError: Expected object of type bytes or bytearray, got: <class 'str'>。使用 "rb" 而不是 "r" 打开解决了问题。
    • @Ousret 也可以在pypi.org/project/charset-normalizer 获得,这意味着您可以使用pip 安装它。我还没有机会尝试,但它看起来很有趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2021-12-30
    相关资源
    最近更新 更多