繁体   English   中英

Python Unencode Unicode HTML十六进制

[英]Python Unencode unicode html hexadecimal

假设我的琴弦上有很多东西

“words words words

有没有办法通过python直接将它们转换成它们代表的字符?

我试过了

h = HTMLParser.HTMLParser()
print h.unescape(x)

但是出现了这个错误:

UnicodeEncodeError:“ ascii”编解码器无法编码位置0-2处的字符:序数不在范围内(128)

我也试过

print h.unescape(x).encode(utf-8) 

但它编码

“ 作为â

什么时候应该是报价

“ 构成U + 201C左双引号字符的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。

问题是您无法正确解码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库中可能有更好的方法...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM