我找不到一个python包,它可以可靠地转换包含一些html实体的文本。我发现HTMLParser对某些东西有用,但也会破坏很多东西。beauthoulsoup似乎不适合转换成unicode。我怎样才能只使用一个方法返回字符串a-d的unicode表示?在
我认为我遇到的问题是我的一些文本既有unicode字符也有html实体(如示例stringd)。在import HTMLParser
from bs4 import BeautifulSoup
astring = "P&O."
bstring = "& "
cstring = ">"
dstring = "> 150ÎC"
pars = HTMLParser.HTMLParser()
a1 = BeautifulSoup(astring)
a2 = pars.unescape(astring)
print "a1:", a1
print "a2:", a2
b1 = BeautifulSoup(bstring)
b2 = pars.unescape(bstring)
print "b1:", b1
print "b2:", b2
c1 = BeautifulSoup(cstring)
c2 = pars.unescape(cstring)
print "c1:", c1
print "c2:", c2
d1 = BeautifulSoup(dstring)
try: d2 = pars.unescape(dstring)
except:d2 = "HTML Parse Broke!"
print "d1:", d1
print "d2:", d2
其输出如下:
^{pr2}$
编辑三:卡尔哈特的建议让我找到了解决办法。为了防止使用混合字符编码的字符串被破坏,我使用了.decode('utf-8')