经常下下来数据集,打开就是乱码,一下子心情就不好了。
人眼看着乱码也就算了,open file encoding报错?
一些解决编码问题的方法:
1. 记事本
记事本——专治一切花里胡哨,我愿奉之为编码界的咖喱棒
用记事本打开,数据集就看着很舒服~
记事本很聪明,绝大多数情况下它知道总是能知道你数据编码格式,并按照一样的解码格式解码,呈现出人类的字符,至少让你能认出来,这TM是人写的
然后选择另存为,保存为utf-8:
现在再来康康——我又可了~
2. 猜
没错,让我来猜一猜,你编码格式是啥
open(unk_file,"r",encoding=???)
>>> utf-8?
报错
>>> gbk?
报错
>>> gb2312?
报错
>>> iso?
报错
emmm…
来份代码自动猜吧:
import codecs
def handleEncoding(original_file,newfile):
#newfile=original_file[0:original_file.rfind(.)]+'_copy.csv'
f=open(original_file,'rb+')
content=f.read()#读取文件内容,content为bytes类型,而非string类型
source_encoding='utf-8'
#####确定encoding类型
try:
content.decode('utf-8').encode('utf-8')
source_encoding='utf-8'
except:
try:
content.decode('gbk').encode('utf-8')
source_encoding='gbk'
except:
try:
content.decode('gb2312').encode('utf-8')
source_encoding='gb2312'
except:
try:
content.decode('gb18030').encode('utf-8')
source_encoding='gb18030'
except:
try:
content.decode('big5').encode('utf-8')
source_encoding='gb18030'
except:
content.decode('cp936').encode('utf-8')
source_encoding='cp936'
f.close()
#####按照确定的encoding读取文件内容,并另存为utf-8编码:
block_size=4096
with codecs.open(original_file,'r',source_encoding) as f:
with codecs.open(newfile,'w','utf-8') as f2:
while True:
content=f.read(block_size)
if not content:
break
f2.write(content)
代码来自:python中的编码问题:以ascii和unicode为主线
你还可以继续try except…把你知道的所有编码格式都列上去
3.掩耳盗铃
emmm,有时候可能就一两行有编码问题,我不想care
那就ignore吧!
open(unk_file,"r",encoding="utf-8",errors="ignore")
小心点,如果无脑ignore的话,你的BERT就把你喂给他的东西全当UNK
喽!