【发布时间】:2011-03-19 18:35:39
【问题描述】:
我目前正在这样做以将扩展 ascii 字符替换为它们的 HTML-entity-number 等效项:
s.encode('ascii', 'xmlcharrefreplace')
我想做的是转换为等效的 HTML 实体名称(即 © 而不是 ©)。下面的这个小程序显示了我正在尝试做的事情是失败的。除了查找/替换之外,有没有办法做到这一点?
#coding=latin-1
def convertEntities(s):
return s.encode('ascii', 'xmlcharrefreplace')
ok = 'ascii: !@#$%^&*()<>'
not_ok = u'extended-ascii: ©®°±¼'
ok_expected = ok
not_ok_expected = u'extended-ascii: ©®°±¼'
ok_2 = convertEntities(ok)
not_ok_2 = convertEntities(not_ok)
if ok_2 == ok_expected:
print 'ascii worked'
else:
print 'ascii failed: "%s"' % ok_2
if not_ok_2 == not_ok_expected:
print 'extended-ascii worked'
else:
print 'extended-ascii failed: "%s"' % not_ok_2
【问题讨论】:
标签: python html encoding ascii