2016-07-26 4 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

:

  • 문의하기 전에 UTF-8로 파일 전에
  • 인코딩 한자 # encoding: utf-8를 추가 quote

여기 예제 제 생각에는, 변환기 유니 코드가 아스키 예제 인'\\ u524d'가 필요합니다. 또는 http://stackoverflow.com/questions/2365411/python-convert-unicode-to-ascii-without-errors를 확인하십시오. – KingRider

답변

5

파이썬 2 이상에서 작업하고있는 것으로 보입니다.

귀하의 질문이 충분히 명확하지 않기 때문에 해결할 정상적인 방법을 제공합니다.

여기 그것을 해결하기 위해 두 가지 충고 :

# 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) 
관련 문제