zoukankan      html  css  js  c++  java
  • python unicode字节串转成中文问题

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

    Example 2:
    >>> str_ = "Russophoxe9bic, clichd and just plxe9ain 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。

    小结:
    以后遇到奇葩问题要想好关键字再搜,不然很有可能一无所获。

    转自:http://windkeepblow.blog.163.com/blog/static/1914883312013988185783/

  • 相关阅读:
    iOS APM性能统计
    iOS promise
    静态代码检测工具Infer的部署
    ES读写数据的工作原理
    关于 Elasticsearch 内存占用及分配
    Elasticsearch中数据是如何存储的
    ES中的选举机制
    .net core 3.1 webapi解决跨域问题 GET DELETE POST PUT等
    .net framework WEBAPI跨域问题
    Angular前端项目发布到IIS
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/6020658.html
Copyright © 2011-2022 走看看