Convert from unicode chars to HTML entities

Adonis Vargas adonis at REMOVETHISearthlink.net
Sun Jan 28 22:47:26 EST 2007


Adonis Vargas wrote:
[...]
> 
> Its *very* ugly, but im pretty sure you can make it look prettier.
> 
> import htmlentitydefs as entity
> 
> s = u"© and many more..."
> t = ""
> for i in s:
>     if ord(i) in entity.codepoint2name:
>         name = entity.codepoint2name.get(ord(i))
>         entityCode = entity.name2codepoint.get(name)
>         t +="&#" + str(entityCode)
>     else:
>         t += i
> print t
> 
> Hope this helps.
> 
> Adonis

or

import htmlentitydefs as entity

s = u"© and many more..."
t = u""
for i in s:
     if ord(i) in entity.codepoint2name:
         name = entity.codepoint2name.get(ord(i))
         t += "&" + name + ";"
     else:
         t += i
print t

Which I think is what you were looking for.

Adonis



More information about the Python-list mailing list