![](/img/trans.png)
[英]Encoding and then decoding json with non-ascii characters in python 2.7
[英]Probleme encoding characters with Python 2.7
它適用於常規字符,但不適用於é,à等重音字符...下面是程序:
def search():
connection = sqlite3.connect('vocab.sqlite')
cursor = connection.cursor()
sql = "SELECT French, English value FROM Ami "
cursor.execute(sql)
data = cursor.fetchall()
data=sorted(data)
file_open=open('vraiamis.html','w')
for i in data:
a='<a href="'+'http://www.google.fr/#hl=fr&gs_nf=1&cp=4&gs_id=o&xhr=t&q='
a=a+str(i[0]).encode('latin-1')+'">'+str(i[0]).encode('latin-1')+'</a>'+'<br>'
file_open.write(a)
file_open.close()
webbrowser.open('vraiamis.html')
當數據庫中的值包含諸如é,à,ç的特殊字符(不起作用時,我收到以下錯誤消息:UnicodeEncodeError:'ascii'編解碼器無法對位置1處的字符u'\\ xe9'進行編碼:范圍內(128)
在此先感謝您的幫助
嘗試
a=a+i[0].encode('latin-1')+'">' + i[0].encode('latin-1')+'</a>'+'<br>'
等等-您的str()
調用正在嘗試將Unicode轉換為字節串,然后再對其進行解碼。
您可以使用utf-8
編碼編寫vraiamis.html
,以便可以對特殊字符進行編碼。
def search():
import codecs
connection = sqlite3.connect('vocab.sqlite')
cursor = connection.cursor()
sql = "SELECT French, English value FROM Ami "
cursor.execute(sql)
data = cursor.fetchall()
data=sorted(data)
file_open= codecs.open('vraiamis.html', 'w', encoding='utf-8')
for i in data:
a=u'<a href="' + u'http://www.google.fr/#hl=fr&gs_nf=1&cp=4&gs_id=o&xhr=t&q='
a=a + i[0] + u'">' + i[0] + u'</a>' + u'<br>'
file_open.write(a)
file_open.close()
webbrowser.open('vraiamis.html')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.