遇到一个类似于“\u6c5f\u897f\u7701\u4e0a\u9976\u5730\u533a\u6ce2\u9633\u53bf”的字符串,如何直接解析出中文
解决方法:
test_str.encode(‘utf-8’).decode(“unicode-escape”)
代码如下 : test_encode.py
#coding:utf-8
import sys
test_str = '\\u6c5f\\u897f\\u7701\\u4e0a\\u9976\\u5730\\u533a\\u6ce2\\u9633\\u53bf'
print test_str
test_str_new = test_str.encode('utf-8').decode("unicode-escape")
print test_str_new
运行如上代码:python test_encode.py
在屏幕上可以输出:
\u6c5f\u897f\u7701\u4e0a\u9976\u5730\u533a\u6ce2\u9633\u53bf
江西省上饶地区波阳县
但是将输出结果写入到文件中时却报如下的错误:
$python test_encode.py > tt
Traceback (most recent call last):
File "test_encode.py", line 7, in <module>
print test_str_new
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128)
原因:这是因为终端不支持中文显示导致的
解决方法如下:
PYTHONIOENCODING=utf-8 python test_encode.py > tt