python unicode字节串转成中文问题

       如题,其实我的问题很简单,就是在写爬虫的时候拿到网页的信息包含类似“\u65b0\u6d6a\u5fae\u535a\u6ce8\u518c”的字符串,实际上这是unicode的中文编码,对应的中文为“新浪微博注册”。其实我就是想找一个函数让这一串东西显示中文而已,没想到百度了白天找到合适的。遇到这种问题千万不要用什么 “python编码” “unicode中文编码” “unicode解码”这样的关键字去搜,一大堆网页出来毫不相关。
      其实这个问题一个函数搞定,如下:
Example 1:
>>> s = r"\u65b0\u6d6a\u5fae\u535a\u6ce8\u518c"
>>> s
'\\u65b0\\u6d6a\\u5fae\\u535a\\u6ce8\\u518c'
>>> print s
\u65b0\u6d6a\u5fae\u535a\u6ce8\u518c
>>> s = s.decode("unicode_escape");     #就是这个函数
>>> print s
新浪微博注册

 
Example 2:
>>> str_ = "Russopho\xe9bic, clichd and just pl\xe9ain stupid."
>>> print str_
Russopho?bic, clichd and just pl?ain stupid.
>>> str_ = str_.decode("unicode_escape")
>>> print str_
Russophoébic, clichd and just pléain stupid.
(这个方法解决了我在插入数据到mongodb时遇到的“bson.errors.InvalidStringData: strings in documents must be valid UTF-8”问题)
 
附上关于这个问题的相关博客链接:http://www.cnblogs.com/yangze/archive/2010/11/16/1878469.html
 
        另外还有一个与unicode字节串有关的问题,遇到这样的错误提示:Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal。说明我们在对两个字符(串)进行对比的时候等号两边的类型
不一样,可能是一边是unicode字节串,一边是字符串。详见http://stackoverflow.com/questions/3400171/python-utf-8-comparison。
        
小结:
以后遇到奇葩问题要想好关键字再搜,不然很有可能一无所获。
posted @ 2016-08-30 10:12  捕蛇者说  阅读(1057)  评论(0编辑  收藏  举报