Skip to content

Commit fe0df46

Browse files
committed
chardet
1 parent d9039fc commit fe0df46

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

README.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5551,6 +5551,75 @@ im.filter(ImageFilter.CONTOUR).show()
55515551
55525552
![](./img/pillow_filter.png)
55535553
5554+
#### 3 一行代码找到编码
5555+
5556+
兴高采烈地,从网页上抓取一段 `content`
5557+
5558+
但是,一 `print ` 就不那么兴高采烈了,结果看到一串这个:
5559+
5560+
```markdown
5561+
b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python'
5562+
```
5563+
5564+
这是啥? 又 x 又 c 的!
5565+
5566+
再一看,哦,原来是十六进制字节串 (`bytes`),`\x` 表示十六进制
5567+
5568+
接下来,你一定想转化为人类能看懂的语言,想到 `decode`
5569+
5570+
```python
5571+
In [3]: b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python'.decode()
5572+
---------------------------------------------------------------------------
5573+
UnicodeDecodeError Traceback (most recent call last)
5574+
<ipython-input-3-7d0ea6148880> in <module>
5575+
----> 1 b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python'.decode()
5576+
5577+
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte
5578+
```
5579+
5580+
马上,一盆冷水泼头上,抛异常了。。。。。
5581+
5582+
根据提示,`UnicodeDecodeError`,这是 unicode 解码错误。
5583+
5584+
原来,`decode` 默认的编码方法:`utf-8`
5585+
5586+
所以排除 b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python' 使用 `utf-8` 的编码方式
5587+
5588+
可是,这不是四选一选择题啊,逐个排除不正确的!
5589+
5590+
编码方式几十种,不可能逐个排除吧。
5591+
5592+
那就猜吧!!!!!!!!!!!!!
5593+
5594+
**人生苦短,我用Python**
5595+
5596+
**Python, 怎忍心让你受累呢~**
5597+
5598+
尽量三行代码解决问题
5599+
5600+
**第一步,安装 chardet** 它是 char detect 的缩写。
5601+
5602+
**第二步,pip install chardet**
5603+
5604+
**第三步,出结果**
5605+
5606+
```python
5607+
In [6]: chardet.detect(b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python')
5608+
Out[6]: {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
5609+
```
5610+
5611+
编码方法:gb2312
5612+
5613+
解密字节串:
5614+
5615+
```python
5616+
In [7]: b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python'.decode('gb2312')
5617+
Out[7]: '人生苦短,我用Python'
5618+
```
5619+
5620+
目前,`chardet` 包支持的检测编码几十种,如下所示:
5621+
5622+
![image-20200227225346560](./img/image-20200227225346560.png)
55545623
55555624
### 八、 机器学习和深度学必知算法
55565625

img/image-20200227225346560.png

536 KB
Loading

0 commit comments

Comments
 (0)