在Python中将XML/HTML实体转换为Unicode字符串
我正在做一些网页抓取,网站经常使用HTML实体来表示非ascii字符。Python是否有一个实用程序,它接受带有HTML实体的字符串并返回unicode类型 例如: 我回来了:在Python中将XML/HTML实体转换为Unicode字符串,python,html,entities,Python,Html,Entities,我正在做一些网页抓取,网站经常使用HTML实体来表示非ascii字符。Python是否有一个实用程序,它接受带有HTML实体的字符串并返回unicode类型 例如: 我回来了: ǎ 它代表一个带有音调标记的“ǎ”。在二进制中,这表示为16位01ce。我想将html实体转换为值u'\u01ce'您可以在这里找到答案-- EDIT:似乎beautifulsou不转换以十六进制形式编写的实体。它可以是固定的: import copy, re from BeautifulSoup
ǎ
它代表一个带有音调标记的“ǎ”。在二进制中,这表示为16位01ce。我想将html实体转换为值
u'\u01ce'
您可以在这里找到答案--
EDIT:似乎beautifulsou
不转换以十六进制形式编写的实体。它可以是固定的:
import copy, re
from BeautifulSoup import BeautifulSoup
hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
# replace hexadecimal character reference by decimal one
hexentityMassage += [(re.compile('&#x([^;]+);'),
lambda m: '&#%d;' % int(m.group(1), 16))]
def convert(html):
return BeautifulSoup(html,
convertEntities=BeautifulSoup.HTML_ENTITIES,
markupMassage=hexentityMassage).contents[0].string
html = '<html>ǎǎ</html>'
print repr(convert(html))
# u'\u01ce\u01ce'
导入副本,重新
从BeautifulSoup导入BeautifulSoup
hexentityMassage=copy.copy(BeautifulSoup.MARKUP\u)
#将十六进制字符引用替换为十进制字符引用
hexentityMassage+=[(重新编译('([^;]+);'),
lambda m:'%d;'%int(m.group(1,16))]
def转换(html):
返回美化组(html,
convertEntities=BeautifulSoup.HTML\u实体,
markupMassage=hexentityMassage)。内容[0]。字符串
html='ǎǎ'
打印报告(转换(html))
#u'\u01ce\u01ce'
编辑:
在这种情况下,使用
htmlentitydefs
标准模块和unichr()
的函数可能更合适。使用内置的unichr
——美化组不是必需的:
>>> entity = 'ǎ'
>>> unichr(int(entity[3:],16))
u'\u01ce'
Python有这个模块,但它不包括一个取消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)
这是一个函数,可以帮助您正确地将实体转换回utf-8字符
def unescape(text):
"""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.
from Fredrik Lundh
2008-01-03: input only unicode characters string.
http://effbot.org/zone/re-sub.htm#unescape-html
"""
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:
print "Value Error"
pass
else:
# named entity
# reescape the reserved characters.
try:
if text[1:-1] == "amp":
text = "&amp;"
elif text[1:-1] == "gt":
text = "&gt;"
elif text[1:-1] == "lt":
text = "&lt;"
else:
print text[1:-1]
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
print "keyerror"
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
不确定堆栈溢出线程不包含“;”的原因在搜索/替换(即lambda m:'%d**)中,如果不这样做,则BeautifulSoup可能会呕吐,因为相邻字符可以解释为HTML代码的一部分(即'B表示'Blackout). 这对我来说更有效:
import re
from BeautifulSoup import BeautifulSoup
html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">'Blackout in a can; on some shelves despite ban</a>'
hexentityMassage = [(re.compile('&#x([^;]+);'),
lambda m: '&#%d;' % int(m.group(1), 16))]
soup = BeautifulSoup(html_string,
convertEntities=BeautifulSoup.HTML_ENTITIES,
markupMassage=hexentityMassage)
重新导入
从BeautifulSoup导入BeautifulSoup
html_字符串=“”
hexentityMassage=[(重新编译('([^;]+);'),
lambda m:'%d;'%int(m.group(1,16))]
soup=BeautifulSoup(html_字符串,
convertEntities=BeautifulSoup.HTML\u实体,
markupMassage=hexentityMassage)
html#u string=re.sub('([^;]+);',lambda m:'%d;'%int(m.group(1),16),html#string)
另一种选择是,如果您有lxml:
>>> import lxml.html
>>> lxml.html.fromstring('ǎ').text
u'\u01ce'
标准库自己的HTMLParser有一个未记录的函数unescape(),它的功能与您认为的完全相同: 直到Python 3.4: Python 3.4+:
import html
html.unescape('© 2010') # u'\xa9 2010'
html.unescape('© 2010') # u'\xa9 2010'
如果您使用的是Python 3.4或更新版本,只需使用:
另一个解决方案是内置库xml.sax.saxutils(用于html和xml)。但是,它将仅转换>、&和<
from xml.sax.saxutils import unescape
escaped_text = unescape(text_to_escape)
以下是Python 3版本的:
主要变化涉及
htmlentitydefs
即现在的html.entities
和unichr
即现在的chr
。请参见此图。此解决方案不适用于以下示例:print BeautifulSoup(“ǎ;”,convertEntities=BeautifulSoup.HTML_ENTITIES)。此方法返回相同的HTML实体注意:此方法仅适用于BeautifulSoup 3,自2012年以来已弃用并被视为遗留。BeautifulSoup 4自动处理类似的HTML实体。@MartijnPieters:正确。在现代Python上是一个更好的选择。如果您只想解码HTML实体,则根本不需要使用BeatifulSoup。@MartiInputers:在旧Python版本上,除非HTMLParser.HTMLParser().unescape()
hack对您有效,否则使用BeatifulSoup可能比手动定义unescape()更好(提供纯Python库而不是函数的复制粘贴)。为什么这个答案被修改了?对我来说似乎很有用。因为那个人想要unicode字符而不是utf-8字符。我想:)谢谢你发现了这个错误。我编辑过,绝对是。为什么不在stdlib中?看看它的代码,它似乎不适用于&
等等,是吗?刚刚成功测试了&;但这需要您自动且明确地知道编码的Unicode字符在字符串中的位置,而这是您无法知道的。您需要尝试…捕获出错时产生的异常。unichar
已在python3中删除。对那个版本有什么建议吗?。函数的to unescape()。Python的HTMLPasser文档中没有记录此方法,并且源代码中有一条注释说明此方法仅供内部使用。然而,它的工作原理类似于Python2.6到2.7中的treat,并且可能是最好的解决方案。在版本2.6之前,它只会解码命名实体,如&代码>或
。它在Python 3.4中以html.unescape()
函数的形式公开,并使用utf-8字符串提升UnicodeDecodeError
。您必须先对它进行解码('utf-8')
或者使用xml.sax.saxutils.unescape
。但是要小心,因为如果没有特殊字符,这也可能返回类型为str
的对象。最佳解决方案
import html
s = html.unescape(s)
from xml.sax.saxutils import unescape
escaped_text = unescape(text_to_escape)
import re
import html.entities
def unescape(text):
"""
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 fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return chr(int(text[3:-1], 16))
else:
return chr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = chr(html.entities.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)