python之chardet操作 编码&解码

发布时间 2023-12-15 17:37:14作者: 3ξ
# python之编码&解码
"""
python中有两种类型,字符串和字节
但是字节的编码是什么我们不知道,所以解码不好解决, chardet解决了这个问题
pip install chardet
"""

# 字节 ---> 字符串
import chardet

temp_bytes = b'hello word'
temp_str = temp_bytes.decode("utf8")
print(f"temp_str:{temp_str}")

# 字符串 ----> 字节
temp_str = "八角寒冰草,烈火杏娇疏"
temp_bytes = temp_str.encode("utf8")
print(f"temp_bytes:{temp_bytes}")

# ----------------------------------------------------------
# chardet功能检测编码
temp_bytes = '八角寒冰草,烈火杏娇疏'.encode("gbk")
detected = chardet.detect(temp_bytes)
print(f"detected:{detected}")


# 根据上述功能,我们就可以知道他是什么编码,从而解码 | 对于爬虫也适用, res.content是字节 res.text是字符串
temp_bytes = '八角寒冰草,烈火杏娇疏'.encode() # 条件1,我获取一个字节,这个编码未知
detected_encoding = chardet.detect(temp_bytes)["encoding"]
temp_str = "八角寒冰草,烈火杏娇疏".encode(detected_encoding).decode('utf-8')# 条件二,使用该字符串--编码未知--解码utf8
print(f"temp_str:{temp_str}")


#输出
# temp_str:hello word
# temp_bytes:b'# \xe5\x85\xab\xe8\xa7\x92\xe5\xaf\x92\xe5\x86\xb0\xe8\x8d\x89,\xe7\x83\x88\xe7\x81\xab\xe6\x9d\x8f\xe5\xa8\x87\xe7\x96\x8f'
# detected:{'encoding': 'KOI8-R', 'confidence': 0.2070506607641618, 'language': 'Russian'}
# temp_str:八角寒冰草,烈火杏娇疏