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

2017-08-31 00:36:43 +08:00
 he458361789
3805 次点击
所在节点    Python
6 条回复
apoclast
2017-08-31 00:50:30 +08:00
没说要 html encode 吗, 那这样吧
```
';'.join(['&#%04x' % ord(c) for c in "你好啊".decode("utf8")])
```
apoclast
2017-08-31 00:51:51 +08:00
仔细一看少了个 x 呀
';'.join(['&#x%04x' % ord(c) for c in "你好啊".decode("utf8")])
he458361789
2017-08-31 01:04:03 +08:00
@apoclast O(∩_∩)O 谢谢大神
imn1
2017-08-31 07:03:17 +08:00
>>> 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
2017-08-31 07:39:20 +08:00
yucongo
2017-09-04 19:16:33 +08:00
import html; html.unescape('你好你好') # '你好你好'

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

html.unescape('你好你好') # '你好你好'

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/387050

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX