python 中遇到 UnicodeEncodeError 的解决方法之一

我最近玩 python 遇到使用 json.loads 转换 json 内容时,如果里面包含Ⅰ·Ⅱ·Ⅲ·Ⅳ·Ⅴ·Ⅵ·Ⅶ·Ⅷ·Ⅸ·Ⅹ·Ⅺ·Ⅻ 这些特殊字符时,就会报错。
UnicodeEncodeError: ‘ascii’ codec can’t encode character ‘\uff1a’ in position 40: ordinal not in range(128)
报错代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.5/urllib/request.py", line 466, in open
response = self._open(req, data)
File "/usr/lib/python3.5/urllib/request.py", line 484, in _open
'_open', req)
File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
result = func(*args)
File "/usr/lib/python3.5/urllib/request.py", line 1297, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/usr/lib/python3.5/urllib/request.py", line 1254, in do_open
h.request(req.get_method(), req.selector, req.data, headers)
File "/usr/lib/python3.5/http/client.py", line 1107, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python3.5/http/client.py", line 1142, in _send_request
self.putrequest(method, url, **skips)
File "/usr/lib/python3.5/http/client.py", line 984, in putrequest
self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode character '\uff1a' in position 40: ordinal not in range(128)

这个问题困扰我好几天,中间折腾的过程就不多说了。
下面说一下我的解法方法,灵感来自上面这段报错代码的第 17 和 18 行。
首先用 vi 或 nano 等编辑器,打开 /usr/lib/python3.5/http/client.py 这个文件,然后定位到 984 行。将 self._output(request.encode('ascii')) 修改成 self._output(request.encode('utf-8'))。重新跑代码后完美解决。