V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wzyefd
V2EX  ›  Python

求教 Python 里面处理 unicode 的问题

  •  
  •   wzyefd · 2015-05-29 12:48:17 +08:00 · 2692 次点击
    这是一个创建于 3226 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题是这样的

    我有一个dict叫content.
    其中 content['title']的值是'aaaa\u2019bbbb'
    我该如何把它转换成"aaaa'bbbb"

    尝试了
    python
    text=content['title']
    result=re.search(r'(\\u\d\d\d\d)',text)
    utf8_value=result.encode('utf-8')
    final=re.sub(r'\\u\d\d\d\d',utf8_value,text)

    本想用 u'aaaa\u2019bbbb'.encode('utf-8'),但是这里不知道该怎样写出u'aaaa\u2019bbbb',尝试了(u'%s' % result).encode('utf-8'),没有用

    7 条回复    2015-05-29 17:36:36 +08:00
    bottleimp
        1
    bottleimp  
       2015-05-29 13:07:25 +08:00
    不明白你说的意思, 不是直接就可以吗, python2.7
    ```
    In [4]: s = u'aaaa\u2019bbbb'

    In [5]: s
    Out[5]: u'aaaa\u2019bbbb'

    In [6]: print s
    aaaa’bbbb
    ```
    Sylv
        2
    Sylv  
       2015-05-29 13:23:34 +08:00 via iPhone
    'aaaa\u2019bbbb'.decode('unicode_escape')

    字符串中的 '\u2019' 并不是一个 Unicode 字符,而是 6 个字符
    yahoo21cn
        3
    yahoo21cn  
       2015-05-29 13:24:30 +08:00
    content['title'] = content['title'].replace(u"’", u"'")
    wzyefd
        4
    wzyefd  
    OP
       2015-05-29 14:28:54 +08:00
    @bottleim
    @Sylv
    @yahoo21cn

    恩,找到原因是,确实\u2019是"’"而不是"'"
    fzinfz
        5
    fzinfz  
       2015-05-29 14:44:20 +08:00
    unicode还是用PY3吧。。。
    ming2281
        6
    ming2281  
       2015-05-29 15:38:36 +08:00
    =>使用Python3.x
    =>全部使用Unicode, 如 name = u"lucy" regx_pattern = ur"xx"
    =>使用utf-8编码当做桥梁

    其中第三种方法在Python2中非常好,需要首先了解字符编码问题
    imn1
        7
    imn1  
       2015-05-29 17:36:36 +08:00
    json ...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2947 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 15:14 · PVG 23:14 · LAX 08:14 · JFK 11:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.