Die anderen Antworten hier helfen Ihnen mit den aufgelisteten Charakteren und ein paar anderen. Wenn Sie jedoch auch alles andere in Entitätsnamen konvertieren möchten, müssen Sie etwas anderes tun. Zum Beispiel, wenn á
in á
konvertiert werden muss, wird weder cgi.escape
noch html.escape
Ihnen dort helfen.Sie möchten etwas tun, das html.entities.entitydefs
verwendet, das nur ein Wörterbuch ist. (Der folgende Code wird für Python 3.x gemacht, aber es gibt ein Teil-Versuch es kompatibel mit 2.x zu machen, um Ihnen eine Vorstellung zu geben):
# -*- 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.
Danke für 'quote = true' in' cgi. Escape – sidx
Beachten Sie, dass einige Ihrer Ersetzungen nicht HTML-kompatibel sind. Zum Beispiel: https://www.w3.org/TR/xhtml1/#C_16 Anstelle von ', verwenden Sie ' Ich denke, ein paar andere wurden zum HTML4-Standard hinzugefügt, aber das war nicht. – leetNightshade