如何在Python中将扩展ASCII转换为HTML实体名称?
我现在正在做的是把扩展的ASCII字符替换成它们对应的HTML实体数字形式:
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
5 个回答
2
编辑
其他人提到了我之前不知道的 htmlentitydefs
。用我的代码可以这样来实现:
from htmlentitydefs import entitydefs as symbols
for tag, val in symbols.iteritems():
mystr = mystr.replace("&{0};".format(tag), val)
这样应该就能正常工作了。
2
你想要的是 htmlentitydefs
吗?
import htmlentitydefs
htmlentitydefs.codepoint2name.get(ord(c),c)
1
更新 这是我选择的解决方案,并且我做了一个小修改,以确保entitydefs中包含我们所拥有的字符的映射。
def convertEntities(s):
return ''.join([getEntity(c) for c in s])
def getEntity(c):
ord_c = ord(c)
if ord_c > 127 and ord_c in htmlentitydefs.codepoint2name:
return "&%s;" % htmlentitydefs.codepoint2name[ord_c]
return c