jbe*_*ley 5 python python-3.x chardet
我正在尝试使用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)
Run Code Online (Sandbox Code Playgroud)
它有效,但它只读取文件的第一行。我尝试使用简单循环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))
Run Code Online (Sandbox Code Playgroud)
在我的例子中,我有一个我认为具有多种编码格式的文件,并编写了以下内容来“逐行”测试它。编辑:尽管我后来发现“逐行”方法似乎也会导致 Chardet 提出一些“误报”。
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3223 次 |
| 最近记录: |