我有一个带有如下符号的字符串:
'
这显然是一个撇号。
我尝试了 saxutils.unescape() 没有任何运气并尝试了 urllib.unquote()
我该如何解码?谢谢!
我有一个带有如下符号的字符串:
'
这显然是一个撇号。
我尝试了 saxutils.unescape() 没有任何运气并尝试了 urllib.unquote()
我该如何解码?谢谢!
看看这个问题。您正在寻找的是“html 实体解码”。通常,您会发现一个名为“htmldecode”之类的函数可以执行您想要的操作。Django 和 Cheetah 都提供了和 BeautifulSoup 一样的功能。
如果您不想使用库并且所有实体都是数字的,那么另一个答案将非常有用。
试试这个:(在这里找到)
from htmlentitydefs import name2codepoint as n2cp
import re
def decode_htmlentities(string):
"""
Decode HTML entities–hex, decimal, or named–in a string
@see http://snippets.dzone.com/posts/show/4569
>>> u = u'E tu vivrai nel terrore - L'aldilà (1981)'
>>> print decode_htmlentities(u).encode('UTF-8')
E tu vivrai nel terrore - L'aldilà (1981)
>>> print decode_htmlentities("l'eau")
l'eau
>>> print decode_htmlentities("foo < bar")
foo < bar
"""
def substitute_entity(match):
ent = match.group(3)
if match.group(1) == "#":
# decoding by number
if match.group(2) == '':
# number is in decimal
return unichr(int(ent))
elif match.group(2) == 'x':
# number is in hex
return unichr(int('0x'+ent, 16))
else:
# they were using a name
cp = n2cp.get(ent)
if cp: return unichr(cp)
else: return match.group()
entity_re = re.compile(r'&(#?)(x?)(\w+);')
return entity_re.subn(substitute_entity, string)[0]
最强大的解决方案似乎是Python 名人 Fredrik Lundh 的这个函数。它不是最短的解决方案,但它可以处理命名实体以及十六进制和十进制代码。