2016-07-26 7 views
3

私は、パラメータのリストをエンコードするために、次のコードを使用:漢字をURLエンコードする方法は?

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以降で作業しているようです。

あなたの質問が十分ではないので、私はそれを解決する通常の方法を提供しています。

ここでそれを修正するには、2つのアドバイスです:

  • コールquote

前にUTF-8に# encoding: utf-8

  • あなたのファイルの前にエンコード中国語の文字を追加しますが、ここでは例です:

    # 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) 
    
    関連する問題