我目前这样做是为了将扩展ascii字符替换为它们的HTML-entity-number等效项:
s.encode('ascii', 'xmlcharrefreplace')我想要做的是转换成HTML-entity-name的等价物(即©而不是©)。下面这个小程序显示了我正在尝试做的失败的事情。除了查找/替换之外,还有什么方法可以做到这一点吗?
#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发布于 2010-07-23 04:13:41
更新这是我要使用的解决方案,通过一个小的修复来检查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发布于 2010-07-23 04:00:21
编辑
其他人提到了我从未听说过的htmlentitydefs。它将以这种方式与我的代码一起工作:
from htmlentitydefs import entitydefs as symbols
for tag, val in symbols.iteritems():
mystr = mystr.replace("&{0};".format(tag), val)这应该是可行的。
发布于 2010-07-23 04:01:50
htmlentitydefs是你想要的吗?
import htmlentitydefs
htmlentitydefs.codepoint2name.get(ord(c),c)https://stackoverflow.com/questions/3312810
复制相似问题