【问题标题】:Locating fragments of non-Latin-1 text in a mostly-Latin-1 file?在主要是拉丁语 1 文件中定位非拉丁语 1 文本的片段?
【发布时间】:2012-02-04 01:03:01
【问题描述】:

我认为英文 .txt 是 Latin-1,但它可能包含其他编码的片段。是否有库或工具可以定位这些片段?

我知道 Python chardat 库之类的东西,但我特意寻找一种工具来测试 Latin-1 文件并检测异常。即使是常规检测库也可以,如果它能够告诉我它检测到非拉丁 1 模式的点并给我索引。

命令行工具和 Python 库尤其受欢迎。

【问题讨论】:

  • 我感觉到你的痛苦,你有没有尝试过类似enca的方法?
  • Enca 看起来很完美,但奇怪的是,它似乎不支持英语。只是一堆东欧语言。真的很奇怪,因为有大量的英文文档。
  • 您能举出异常的例子吗?您在寻找 UTF8 还是其他 8 位字符集?代码点 0x80-0x9F 在拉丁语中未定义,但除此之外,所有序列都是有效的。如果您正在寻找类似 KOI-8r 与拉丁语混合的内容,字母频率和 n-gram 字母序列是一个很好的启发式方法,但无法确定每个字符。
  • 对于英语,您可以容忍任何被 7 位包围的单个 8 位字符,可能标记为手动检查任何相邻 8 位字符的短序列,并且默认为非英语任何更长的序列8 位数据。
  • 您是否考虑过让生成文件的人感到痛苦?

标签: python unicode encoding latin1


【解决方案1】:

Latin-1(或者您的意思是它带有欧元符号的 latin-15 变体?)并不那么容易检测。

简单的方法是检查是否确实使用了一些未使用的字符 (见表here)——如果有,那就是有问题。但是,要检测更细微的违规行为,需要实际检查该语言是否是其中一种,使用 latin-1。否则,无法区分 8 位编码。最好不要一开始就混合 8 位编码,而不以某种方式标记编码的变化......

【讨论】:

    【解决方案2】:

    您认为文件 (1) 是 Latin-1 (2) 可能包含其他编码的片段的理由是什么?文件有多大?什么是“常规检测库”?您是否考虑过它可能是 Windows 编码的可能性,例如cp1252?

    一些粗略的诊断:

    # preliminaries
    text = open('the_file.txt', 'rb').read()
    print len(text), "bytes in file"
    
    # How many non-ASCII bytes?
    print sum(1 for c in text if c > '\x7f'), "non-ASCII bytes"
    
    # Will it decode as UTF-8 OK?
    try:
        junk = text.decode('utf8')
        print "utf8 decode OK"
    except UnicodeDecodeError, e:
        print e
    
    # Runs of more than one non-ASCII byte are somewhat rare in single-byte encodings
    # of languages written in a Latin script ...
    import re
    runs = re.findall(r'[\x80-\xff]+', text)
    nruns = len(runs)
    print nruns, "runs of non-ASCII bytes"
    if nruns:
        avg_rlen = sum(len(run) for run in runs) / float(nruns)
        print "average run length: %.2f bytes" % avg_rlen
    # then if indicated you could write some code to display runs in context ...
    

    【讨论】:

      猜你喜欢
      • 2022-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2021-11-01
      • 2018-04-22
      相关资源
      最近更新 更多