我正在尝试使用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': ''}
我想知道增加它读取的行数是否会提高编码的可信度。
任何帮助都将不胜感激。
发布于 2018-04-03 03:35:51
我对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()发布于 2019-02-27 09:34:04
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时破裂。对于非常大的文件很有用。
发布于 2021-05-26 12:09:32
另一个没有使用python-magic包将文件加载到内存的示例
import magic
def detect(
file_path,
):
return magic.Magic(
mime_encoding=True,
).from_file(file_path)https://stackoverflow.com/questions/46037058
复制相似问题