[英]Convert a symbol to its 4 digit unicode escape representation and vice versa
[英]Convert HTML entities to Unicode and vice versa
如何在 Python 中将 HTML 实体转换为 Unicode 和反之亦然?
至于“反之亦然”(我需要自己,导致我找到这个没有帮助的问题,然后是另一个有答案的网站):
u'some string'.encode('ascii', 'xmlcharrefreplace')
将返回一个纯字符串,其中任何非 ascii 字符都转换为 XML (HTML) 实体。
你需要有BeautifulSoup 。
from BeautifulSoup import BeautifulStoneSoup
import cgi
def HTMLEntitiesToUnicode(text):
"""Converts HTML entities to unicode. For example '&' becomes '&'."""
text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
return text
def unicodeToHTMLEntities(text):
"""Converts unicode to HTML entities. For example '&' becomes '&'."""
text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace')
return text
text = "&, ®, <, >, ¢, £, ¥, €, §, ©"
uni = HTMLEntitiesToUnicode(text)
htmlent = unicodeToHTMLEntities(uni)
print uni
print htmlent
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &, ®, <, >, ¢, £, ¥, €, §, ©
Python 2.7 和 BeautifulSoup4 的更新
Unescape -- Unicode HTML 到 unicode 与htmlparser
(Python 2.7 标准库):
>>> escaped = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood'
>>> from HTMLParser import HTMLParser
>>> htmlparser = HTMLParser()
>>> unescaped = htmlparser.unescape(escaped)
>>> unescaped
u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood'
>>> print unescaped
Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood
Unescape -- Unicode HTML 到 unicode 与bs4
(BeautifulSoup4):
>>> html = '''<p>Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood</p>'''
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> soup.text
u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood'
>>> print soup.text
Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood
转义 -- Unicode 到 unicode HTML 与bs4
(BeautifulSoup4):
>>> unescaped = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood'
>>> from bs4.dammit import EntitySubstitution
>>> escaper = EntitySubstitution()
>>> escaped = escaper.substitute_html(unescaped)
>>> escaped
u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood'
正如hekevintran回答所暗示的,您可以使用cgi.escape(s)
对字符串进行编码,但请注意,在 function 中,quote 的编码默认为 false,并且将quote=True
关键字参数与您的字符串一起传递可能是个好主意。 但即使通过quote=True
, function 也不会转义单引号( "'"
)(由于这些问题, function 自 3.2 版以来已被弃用)
建议使用html.escape(s)
而不是cgi.escape(s)
。 (版本 3.2 中的新功能)
html.unescape(s)
已在 3.4 版本中引入。
因此,在 python 3.4 中,您可以:
html.escape(text).encode('ascii', 'xmlcharrefreplace').decode()
将特殊字符转换为 HTML 实体。html.unescape(text)
用于将 HTML 实体转换回纯文本表示形式。$ python3 -c "
> import html
> print(
> html.unescape('&©—')
> )"
&©—
$ python3 -c "
> import html
> print(
> html.escape('&©—')
> )"
&©—
$ python2 -c "
> from HTMLParser import HTMLParser
> print(
> HTMLParser().unescape('&©—')
> )"
&©—
$ python2 -c "
> import cgi
> print(
> cgi.escape('&©—')
> )"
&©—
HTML 只严格要求&
(与号)和<
(左尖括号/小于号)被转义。 https://html.spec.whatwg.org/multipage/parsing.html#data-state
对于python3
使用html.unescape()
:
import html
s = "&"
decoded = html.unescape(s)
# &
如果像我这样的人想知道为什么有些实体编号(代码)像™ (for trademark symbol), € (for euro symbol)
™ (for trademark symbol), € (for euro symbol)
™ (for trademark symbol), € (for euro symbol)
未正确编码,原因是在 ISO-8859-1(又名 Windows-1252)中未定义这些字符。
另请注意,从 html5 开始的默认字符集是 utf-8 它是 html4 的 ISO-8859-1
所以,我们将不得不以某种方式解决(首先找到并替换那些)
Mozilla 文档中的参考(起点)
https://developer.mozilla.org/en-US/docs/Web/Guide/Localizations_and_character_encodings
我使用以下 function 将从 xls 文件中提取的 unicode 转换为 html 文件,同时保留 xls 文件中的特殊字符:
def html_wr(f, dat):
''' write dat to file f as html
. file is assumed to be opened in binary format
. if dat is nul it is replaced with non breakable space
. non-ascii characters are translated to xml
'''
if not dat:
dat = ' '
try:
f.write(dat.encode('ascii'))
except:
f.write(html.escape(dat).encode('ascii', 'xmlcharrefreplace'))
希望这对某人有用
#!/usr/bin/env python3
import fileinput
import html
for line in fileinput.input():
print(html.unescape(line.rstrip('\n')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.