假设我有很多像
这样的东西的字符串“words words words
有没有办法将这些通过python直接转换为它们代表的字符?
我试过
h = HTMLParser.HTMLParser()
print h.unescape(x)
但得到了这个错误:
UnicodeEncodeError:' ascii'编解码器不能对位置0-2中的字符进行编码:序数不在范围内(128)
我也试过
print h.unescape(x).encode(utf-8)
但它编码
“
为â
什么时候应该是报价
答案 0 :(得分:1)
“
形成 UTF-8字节序列。那里的东西很重要。正确的编码应该是“
。
您可以使用HTML解析器来解决此问题,但您需要修复生成的Mochibake:
>>> import HTMLParser
>>> h = HTMLParser.HTMLParser()
>>> x = '“'
>>> h.unescape(x)
u'\xe2\x80\x9c'
>>> h.unescape(x).encode('latin1')
'\xe2\x80\x9c'
>>> h.unescape(x).encode('latin1').decode('utf8')
u'\u201c'
>>> print h.unescape(x).encode('latin1').decode('utf8')
“
如果打印仍然给你一个UnicodeEncodeError,那么你的终端或控制台配置不正确,并且Python无法编码为ASCII。
答案 1 :(得分:0)
问题是你无法正确解码unicode ...你需要将它从unicode转换为utf8
x="“words words words"
h = HTMLParser.HTMLParser()
msg=h.unescape(x) #this converts it to unicode string ..
downcast = "".join(chr(ord(c)&0xff) for c in msg) #convert it to normal string (python2)
print downcast.decode("utf8")
在HTMLParser库中可能有更好的方法...