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
he458361789
V2EX  ›  Python

经常看到 html 源码有这种你好你好 编码。求用 Python 把中文转成这个编码的实现方法

  •  
  •   he458361789 · 2017-08-31 00:36:43 +08:00 · 3782 次点击
    这是一个创建于 2436 天前的主题,其中的信息可能已经有所发展或是发生改变。
    6 条回复    2017-09-04 19:16:33 +08:00
    apoclast
        1
    apoclast  
       2017-08-31 00:50:30 +08:00
    没说要 html encode 吗, 那这样吧
    ```
    ';'.join(['&#%04x' % ord(c) for c in "你好啊".decode("utf8")])
    ```
    apoclast
        2
    apoclast  
       2017-08-31 00:51:51 +08:00
    仔细一看少了个 x 呀
    ';'.join(['&#x%04x' % ord(c) for c in "你好啊".decode("utf8")])
    he458361789
        3
    he458361789  
    OP
       2017-08-31 01:04:03 +08:00
    @apoclast O(∩_∩)O 谢谢大神
    imn1
        4
    imn1  
       2017-08-31 07:03:17 +08:00   ❤️ 1
    >>> import html.parser
    >>> h = html.parser.HTMLParser()
    >>> s = h.unescape('© 2010')
    >>> s
    u'\xa9 2010'
    >>> print s
    © 2010
    >>> s = h.unescape('© 2010')
    >>> s
    u'\xa9 2010'


    >>> '袈'.encode("unicode-escape")
    b'\\u8888'
    >>> chr(int('8888', 16))
    '袈'

    >>> h.unescape('♥')
    '♥'
    >>> h.unescape('♥')
    '♥'
    >>> h.unescape('♥')
    '♥'
    >>> '♥'.encode("unicode-escape")
    b'\\u2665'
    >>> chr(int('2665', 16))
    '♥'

    >>> import html.entities as h
    >>> h.name2codepoint['hearts']
    9829

    >>> a='汉字먀니'.encode('utf-8')
    >>> b=re.findall(b'\xe4[\xb8-\xff][\x00-\xff]|[\xe5-\xe8][\x00-\xff][\x00-\xff]|\xe9[\x00-\xbe][\x00-\xff]', a)
    >>> b
    [b'\xe6\xb1\x89', b'\xe5\xad\x97']
    Sanko
        5
    Sanko  
       2017-08-31 07:39:20 +08:00 via Android   ❤️ 1
    yucongo
        6
    yucongo  
       2017-09-04 19:16:33 +08:00   ❤️ 1
    import html; html.unescape('你好你好') # '你好你好'

    '你好你好'.encode("ascii", errors='xmlcharrefreplace').decode("ascii") # '你好你好' # 10 进制, 上面的 你好你好 是 16 进制

    html.unescape('你好你好') # '你好你好'
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1799 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:53 · PVG 08:53 · LAX 17:53 · JFK 20:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.