Các câu trả lời khác ở đây sẽ trợ giúp như các ký tự bạn đã liệt kê và một vài người khác. Tuy nhiên, nếu bạn cũng muốn chuyển đổi mọi thứ khác thành tên thực thể, bạn sẽ phải làm một việc khác. Ví dụ: nếu á
cần phải được chuyển đổi thành á
, không phải cgi.escape
cũng không phải html.escape
sẽ giúp bạn ở đó.Bạn sẽ muốn làm một cái gì đó như thế này sử dụng html.entities.entitydefs
, mà chỉ là một từ điển. (Mã sau đây được tạo cho Python 3.x, nhưng có một nỗ lực một phần để làm cho nó tương thích với 2.x để cung cấp cho bạn một ý tưởng):
# -*- 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.
Cảm ơn bạn đã báo giá «True' trong' cgi. escape' – sidx
Lưu ý, một số thay thế của bạn không tuân thủ HTML. Ví dụ: https://www.w3.org/TR/xhtml1/#C_16 Thay vì ', hãy sử dụng ' Tôi đoán một số khác đã được thêm vào tiêu chuẩn HTML4, nhưng không phải vậy. – leetNightshade