【问题标题】:Probleme encoding characters with Python 2.7使用 Python 2.7 编码字符有问题
【发布时间】:2012-02-23 13:35:34
【问题描述】:

它适用于常规字符,但不适用于 é,à 等重音字符... 这是程序:

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' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)

提前感谢您的帮助

【问题讨论】:

    标签: python database encoding


    【解决方案1】:

    试试

    a=a+i[0].encode('latin-1')+'">' + i[0].encode('latin-1')+'</a>'+'<br>'
    

    等 - 您的 str() 调用试图在您解码之前将 unicode 转换为字节串。

    【讨论】:

      【解决方案2】:

      你可以把你的vraiamis.html写成utf-8编码,这样你的特殊字符就可以被编码了。

      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')
      

      【讨论】:

      • 对不起,编码不起作用它返回错误消息
      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 2017-11-22
      • 2012-02-22
      • 1970-01-01
      • 2020-04-04
      • 2018-07-01
      相关资源
      最近更新 更多