【问题标题】:Using Chardet to find encoding of very large file使用 Chardet 查找非常大文件的编码
【发布时间】:2017-09-04 12:27:22
【问题描述】:

我正在尝试使用Chardet 以制表符分隔格式推断一个非常大的文件(>400 万行)的编码。

目前,我的脚本可能由于文件的大小而出现问题。我想将其缩小到加载文件的前 x 行,可能,但是当我尝试使用 readline() 时遇到了困难。

目前的脚本是:

import chardet
import os
filepath = os.path.join(r"O:\Song Pop\01 Originals\2017\FreshPlanet_SongPop_0517.txt")
rawdata = open(filepath, 'rb').readline()


print(rawdata)
result = chardet.detect(rawdata)
print(result)

它可以工作,但它只读取文件的第一行。我尝试使用简单的循环多次调用readline() 效果不佳(可能是脚本以二进制格式打开文件的事实)。

一行的输出是{'encoding': 'Windows-1252', 'confidence': 0.73, 'language': ''}

我想知道增加它读取的行数是否会提高编码置信度。

任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x chardet


    【解决方案1】:

    我对 Chardet 并不是特别有经验,但是在调试我自己的问题时偶然发现了这篇文章,并且很惊讶它没有任何答案。抱歉,如果这对 OP 没有任何帮助为时已晚,但对于其他偶然发现此问题的人:

    我不确定读入更多文件是否会改善猜测的编码类型,但您需要做的就是测试它:

    import chardet
    testStr = b''
    count = 0
    with open('Huge File!', 'rb') as x:
        line = x.readline()
        while line and count < 50:  #Set based on lines you'd want to check
            testStr = testStr + line
            count = count + 1
            line = x.readline()
    print(chardet.detect(testStr))
    

    在我的例子中,我有一个我认为有多种编码格式的文件,并编写了以下内容来“逐行”测试它。

    import chardet
    with open('Huge File!', 'rb') as x:
        line = x.readline()
        curChar = chardet.detect(line)
        print(curChar)
        while line:
            if curChar != chardet.detect(line):
                curChar = chardet.detect(line)
                print(curChar)
            line = x.readline()
    

    【讨论】:

      【解决方案2】:

      UniversalDetector 的另一个例子:

      #!/usr/bin/env python
      from chardet.universaldetector import UniversalDetector
      
      
      def detect_encode(file):
          detector = UniversalDetector()
          detector.reset()
          with open(file, 'rb') as f:
              for row in f:
                  detector.feed(row)
                  if detector.done: break
      
          detector.close()
          return detector.result
      
      if __name__ == '__main__':
          print(detect_encode('example_file.csv'))
      

      当置信度 = 1.0 时中断。对于非常大的文件很有用。

      【讨论】:

        【解决方案3】:

        另一个没有使用python-magic包将文件加载到内存的例子

        import magic
        
        
        def detect(
            file_path,
        ):
            return magic.Magic(
                mime_encoding=True,
            ).from_file(file_path)
        
        

        【讨论】:

          【解决方案4】:
          import chardet
          
          with open(filepath, 'rb') as rawdata:
              result = chardet.detect(rawdata.read(100000))
          result
          

          【讨论】:

          • @JavaSheriff 什么链接?您是否选择了错误的预设评论?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-23
          • 2012-01-30
          相关资源
          最近更新 更多