其一:做个学习的资料记录。其二:分享出来,供大家参考。
这是关于 文件进行编码处理后同过python解码认知的问题。
首先我们应该知道æ–‡å—化ã??、����������等都是需要使用编码才能解读的字符,如果不使用正确的编码格式,那么始终无法进行字符的解读。我们看一个例子:
before = "I'd recommend $, #, 你好 and नमस्ते" #这是一串字符包括了许多的类型
after = before.encode("utf-8",errors="replace") #我们对其进行utf-8的编码处理,并使用错误处理代替
print(after)
b"I'd recommend $, #, \xe4\xbd\xa0\xe5\xa5\xbd and \xe0\xa4\xa8\xe0\xa4\xae\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4\xe0\xa5\x87"
以上的输出结果我们可以看到使用了正确的编码后的输出结果。
before = "I'd recommend $, #, 你好 and नमस्ते"
after = before.encode("ascii",errors="replace") #换成ascii来进行编码
print(after)
b"I'd recommend $, #, ?? and ??????"
可以看出我们使用了错误的编码格式,导致了?的出现。
before = "I'd recommend $, #, 你好 and नमस्ते"
after = before.encode("utf-8",errors="replace")
after = after.decode("utf-8") #这里我们使用decode进行utf-8格式的解码
print(after)
#I'd recommend $, #, 你好 and नमस्ते #获取到了正确的格式
但是如果你使用ascii来解码将会出现错误提示。
utf-8是一种极为普遍的编码格式,对于python来说它的所用代码都是使用utf-8来编码的,这是个好消息。
重点说一下大数据的编码问题,通常我们使用直接读取文件来获得内容,但是有的时候文件存在编码问题,所以我们需要使用正确的编码格式来打开文件。但是文件的编码格式我们不知道,这是chatdet则可以帮助我们有效的解决问题,如下:
data = pd.read_csv("police.csv")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 2: invalid start byte
提示错误,默认的utf-8不能解码。这该如何是好,之时就可以使用chardet模块了:
import chardet
with open("PoliceKillingsUS.csv","rb") as k:
dd = chardet.detect(k.read(10000))
{'encoding': 'ascii', 'confidence': 1, 'language': ''} 从输出我们可以看出这个模块有1的概率认为这是windows-1252的编码格式
所以我们可以使用这个格式来试试
UnicodeDecodeError: 'ascii' codec can't decode byte 0x96 in position 2: ordinal not in range(128) #我去竟然错误了,这个模块什么鬼
不急,这里真是我想说的,其实我们k.read(10000),文件已经读取了很多数据了,但是它还是判断错了。其实在大多数的小数据中它是可以判断正确的,这是这里数据量太大了,所以我们改为k.read(100000):
{'encoding': 'Windows-1252', 'confidence': 0.73, 'language': ''}
这下可以看出来,在读了做了大量的判断后它认为有0.73是windows-1252格式的编码,所以我们再试试。
data = pd.read_csv("PoliceKillingsUS.csv",encoding="Windows-1252")
print(data.head(5))
id name date manner_of_death armed age \
0 3 Tim Elliot 02/01/15 shot gun 53.0
1 4 Lewis Lee Lembke 02/01/15 shot gun 47.0
2 5 John Paul Quintero 03/01/15 shot and Tasered unarmed 23.0
3 8 Matthew Hoffman 04/01/15 shot toy weapon 32.0
4 9 Michael Rodriguez 04/01/15 shot nail gun 39.0
gender race city state signs_of_mental_illness threat_level \
0 M A Shelton WA True attack
1 M W Aloha OR False attack
2 M H Wichita KS False other
3 M W San Francisco CA True attack
4 M H Evans CO False attack
flee body_camera
0 Not fleeing False
1 Not fleeing False
2 Not fleeing False
3 Not fleeing False
4 Not fleeing False
可以看出是没有问题的,所以在读取文件是有效的利用chardet模块,能解决大量的编码问题。以上的k.read(100000)增大数据量只是一种方式。下面还有一种相对比较复杂的方法,但更高级。
from chardet.universaldetector import UniversalDetector
usock = open("PoliceKillingsUS.csv", 'rb')
detector = UniversalDetector()
for line in usock.readlines():
detector.feed(line)
if detector.done: break
detector.close()
usock.close()
print (detector.result)
{'encoding': 'Windows-1252', 'confidence': 0.73, 'language': ''}
这种相对复杂当更高级的方法也可以做出辨认。
最后就是我们可以将我们转换编码后的文本进行保存,这个比较简单:
pd.to_csv("PoliceKillingsUS_utf-8.csv")
OK以上是这次比赛的一部分的收获!