Using urlencode for Devanagari text

限于喜欢 提交于 2020-03-24 00:23:10

问题


The following code:

import simplejson,urllib,urllib2  

query=[u'नेपाल']
urlbase="http://search.twitter.com/search.json"
values={'q':query[0]}
data=urllib.urlencode(values)
req=urllib2.Request(urlbase,data)
response=urllib2.urlopen(req)
json=simplejson.load(response)
print json

throws exception:

SyntaxError: Non-ASCII character '\xe0' in file ques.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

The code works if query contains standard ASCII characters. I tried looking at the suggested link but couldn't figure out how to specify encoding for Devanagari characters.


回答1:


You need to add the UTF-8 header to your file to tell the Python interpreter that there are unicode literals. You also have to encode the parameters as UTF-8. Here's a working version:

# -*- coding: utf-8 -*-
import simplejson,urllib,urllib2  

query=[u'नेपाल']
urlbase="http://search.twitter.com/search.json"
values={'q':query[0].encode('utf-8')}
data=urllib.urlencode(values)
req=urllib2.Request(urlbase,data)
response=urllib2.urlopen(req)
json=simplejson.load(response)
print json


来源:https://stackoverflow.com/questions/8672057/using-urlencode-for-devanagari-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!