Las otras respuestas aquí le ayudarán con, por ejemplo, los caracteres que enumeró y algunos otros. Sin embargo, si también quieres convertir todo lo demás en nombres de entidades, tendrás que hacer otra cosa. Por ejemplo, si se debe convertir á
a á
, ni cgi.escape
ni html.escape
le ayudarán allí.Querrá hacer algo como esto que use html.entities.entitydefs
, que es solo un diccionario. (El siguiente código se hace para Python 3.x, pero hay un intento parcial en lo que es compatible con 2.x para darle una idea):
# -*- coding: utf-8 -*-
import sys
if sys.version_info[0]>2:
from html.entities import entitydefs
else:
from htmlentitydefs import entitydefs
text=";\"áèïøæỳ" #This is your string variable containing the stuff you want to convert
text=text.replace(";", "$ஸ$") #$ஸ$ is just something random the user isn't likely to have in the document. We're converting it so it doesn't convert the semi-colons in the entity name into entity names.
text=text.replace("$ஸ$", ";") #Converting semi-colons to entity names
if sys.version_info[0]>2: #Using appropriate code for each Python version.
for k,v in entitydefs.items():
if k not in {"semi", "amp"}:
text=text.replace(v, "&"+k+";") #You have to add the & and ; manually.
else:
for k,v in entitydefs.iteritems():
if k not in {"semi", "amp"}:
text=text.replace(v, "&"+k+";") #You have to add the & and ; manually.
#The above code doesn't cover every single entity name, although I believe it covers everything in the Latin-1 character set. So, I'm manually doing some common ones I like hereafter:
text=text.replace("ŷ", "ŷ")
text=text.replace("Ŷ", "Ŷ")
text=text.replace("ŵ", "ŵ")
text=text.replace("Ŵ", "Ŵ")
text=text.replace("ỳ", "ỳ")
text=text.replace("Ỳ", "Ỳ")
text=text.replace("ẃ", "&wacute;")
text=text.replace("Ẃ", "&Wacute;")
text=text.replace("ẁ", "ẁ")
text=text.replace("Ẁ", "Ẁ")
print(text)
#Python 3.x outputs: ;"áèïøæỳ
#The Python 2.x version outputs the wrong stuff. So, clearly you'll have to adjust the code somehow for it.
Gracias por 'quote = TRUE en' cgi. escape' – sidx
Tenga en cuenta que algunos de sus reemplazos no son compatibles con HTML. Uno por ejemplo: https://www.w3.org/TR/xhtml1/#C_16 En lugar de ', use ' Supongo que se agregaron algunos otros al estándar HTML4, pero ese no. – leetNightshade