2016-07-26 37 views
3

我用下面的代碼進行編碼參數列表:如何對中文字符進行網址編碼?

params['username'] = user 
params['q'] = q 
params = urllib.quote(params) 

但當q等於香港這是行不通的。將返回以下錯誤:

'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) 

我該如何解決?

+0

我想,你需要使用轉換器unicode來ascii例子'\\ u524d'。或者檢查http://stackoverflow.com/questions/2365411/python-convert-unicode-to-ascii-without-errors – KingRider

回答

5

看來你正在使用Python 2+。

因爲你的問題不夠清楚,我提供了一個正常的解決方法。

這裏有一點建議,以解決它:

  • 調用之前您的文件之前添加# encoding: utf-8
  • 編碼中國字爲UTF-8 quote

這裏的例子:

# encoding: utf-8 

import urllib 


def to_utf8(text): 
    if isinstance(text, unicode): 
     # unicode to utf-8 
     return text.encode('utf-8') 
    try: 
     # maybe utf-8 
     return text.decode('utf-8').encode('utf-8') 
    except UnicodeError: 
     # gbk to utf-8 
     return text.decode('gbk').encode('utf-8') 


if __name__ == '__main__': 
       # utf-8  # utf-8     # unicode   # gdk 
    for _text in ('香港', b'\xe9\xa6\x99\xe6\xb8\xaf', u'\u9999\u6e2f', b'\xcf\xe3\xb8\xdb'): 
     _text = to_utf8(_text) 
     print urllib.quote(_text) 
相關問題