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

py2 怎么将汉字转换为 XML 里表示的&#xxxx 形式?

  •  
  •   oldbird · 2021-01-24 10:43:45 +08:00 · 1684 次点击
    这是一个创建于 1159 天前的主题,其中的信息可能已经有所发展或是发生改变。

    &#xxxx 是什么编码格式? py2 怎么将汉字转换为这种形式? XML 里用的

    6 条回复    2021-01-25 13:48:19 +08:00
    ClericPy
        1
    ClericPy  
       2021-01-24 10:51:36 +08:00
    # -*- coding: utf-8 -*-

    from html import escape

    print(escape(u'中文').encode('ascii', 'xmlcharrefreplace').decode('u8'))

    python - Convert HTML entities to Unicode and vice versa - Stack Overflow - https://stackoverflow.com/questions/701704/convert-html-entities-to-unicode-and-vice-versa
    mxT52CRuqR6o5
        2
    mxT52CRuqR6o5  
       2021-01-24 10:54:05 +08:00
    HTML 转义字符?
    bertonzh
        3
    bertonzh  
       2021-01-24 10:55:23 +08:00   ❤️ 1
    xxxx 是十进制的 unicode,所以你只需要把每个字符转成 code 就行。
    或者 &#xyyyy; 类似 yyyy 是十六进制格式。
    oldbird
        4
    oldbird  
    OP
       2021-01-24 11:44:28 +08:00
    @ClericPy
    打印结果为 ÖÐÎÄ
    怎么让一个汉字对应&#xxxx; ??
    ClericPy
        5
    ClericPy  
       2021-01-24 11:55:12 +08:00
    @oldbird 没懂你说的具体是什么... 举个例子? 我打印的直接丢 HTML 里就是中文俩字

    [Running] python2 -u "demo.py"
    中文
    no1xsyzy
        6
    no1xsyzy  
       2021-01-25 13:48:19 +08:00
    @oldbird 文件不要保存为 GBK
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4674 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:03 · PVG 18:03 · LAX 03:03 · JFK 06:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.