5

我试图用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': ''}

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

任何帮助将不胜感激。

4

4 回答 4

4

我对 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()
于 2018-04-03T03:35:51.283 回答
3

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

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

于 2019-02-27T09:34:04.407 回答
0

python-magic另一个不使用包将文件加载到内存的示例

import magic


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

于 2021-05-26T12:09:32.693 回答
-1
import chardet

with open(filepath, 'rb') as rawdata:
    result = chardet.detect(rawdata.read(100000))
result
于 2021-04-30T12:31:05.880 回答