我正在做一些网页抓取,网站经常使用HTML实体来表示非ascii字符。Python是否有一个实用工具,可以接受包含HTML实体的字符串并返回unicode类型?
例如:
我回来了:
ǎ
它表示带有音调标记的"ǎ“。在二进制中,这表示为16位01ce。我希望将html实体转换为值u'\u01ce'
发布于 2012-09-27 13:34:44
标准库自己的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'
发布于 2008-09-12 01:40:41
Python有htmlentitydefs模块,但没有包含对HTML实体进行反转义符的函数。
Python开发人员Fredrik Lundh ( elementtree等的作者)有这样一个函数on his website,它可以处理十进制、十六进制和命名实体:
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)
发布于 2008-09-11 23:09:09
使用内置的unichr
-- BeautifulSoup不是必需的:
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'\u01ce'
https://stackoverflow.com/questions/57708
复制相似问题