gpt4 book ai didi

python - 使用 Chardet 查找超大文件的编码

转载 作者:太空狗 更新时间:2023-10-30 02:38:47 26 4
gpt4 key购买 nike

我正在尝试使用 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': ''}

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

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

最佳答案

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

关于python - 使用 Chardet 查找超大文件的编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com