使用 Chardet 查找非常大文件的编码

Using Chardet to find encoding of very large file

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

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

时遇到困难

目前的脚本是:

import chardet
import os
filepath = os.path.join(r"O:\Song Pop Originals17\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': ''}

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

如有任何帮助,我们将不胜感激。

我对 Chardet 没有特别的经验,但在调试我自己的问题时遇到了这个 post,并且很惊讶它没有任何答案。抱歉,如果这对 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))

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

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()

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 时中断。适用于非常大的文件。

import chardet

with open(filepath, 'rb') as rawdata:
    result = chardet.detect(rawdata.read(100000))
result

另一个没有使用python-magic

加载文件到内存的例子
import magic


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