在Python中将XML/HTML实体转换为Unicode字符串
我正在做一些网页抓取,很多网站常常用HTML实体来表示非ASCII字符。请问Python有没有工具可以把包含HTML实体的字符串转换成Unicode类型?
举个例子:
我得到的是:
ǎ
这个表示一个带音调符号的“ǎ”。在二进制中,它是用16位的01ce表示的。我想把这个HTML实体转换成值 u'\u01ce'
10 个回答
18
使用内置的 unichr
函数就可以了——其实不需要用到 BeautifulSoup。
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'\u01ce'
60
Python有一个叫做 htmlentitydefs 的模块,但里面并没有提供一个可以将HTML实体转换回普通文本的函数。
Python的开发者Fredrik Lundh(他还写过elementtree等其他东西)在他的网站上提供了这样一个函数 ,这个函数可以处理十进制、十六进制和命名实体:
import re, htmlentitydefs
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
61
标准库里的 HTMLParser 有一个没有文档说明的函数 unescape(),它的功能正如你所想的那样:
在 Python 3.4 之前:
import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'
在 Python 3.4 及之后:
import html
html.unescape('© 2010') # u'\xa9 2010'
html.unescape('© 2010') # u'\xa9 2010'