Python Google Places Api-传递具有正确编码的地址

Python Google Places Api-传递具有正确编码的地址,python,encoding,google-places-api,Python,Encoding,Google Places Api,为了进行googleplacesapi调用,我使用以下函数: def build_URL(search_text='',types_text=''): base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json' key_string = '?key=mykey' query_string = '&

为了进行
googleplacesapi
调用,我使用以下函数:

def build_URL(search_text='',types_text=''):
    base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'     
    key_string = '?key=mykey'                                       
    query_string = '&query='+urllib.quote(search_text)
    sensor_string = '&sensor=false'                                            
    type_string = ''
    if types_text!='':
        type_string = '&types='+urllib.quote(types_text)                        
    url = base_url+key_string+query_string+sensor_string+type_string
    return url
但我作为参数传递的地址存在编码问题:

   print(build_URL(search_text='R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'))
我试过
“R.Fradique Coutinho,1332-圣保罗皮涅罗斯-SP,05416-001,巴西”。编码('utf-8')
,但没有成功。我得到一个错误:

{
error_message: "Invalid request. One of the input parameters contains a non-UTF-8 string.",
html_attributions: [ ],
results: [ ],
status: "INVALID_REQUEST"
}
我的脚本的顶部还有
#-*-编码:utf-8-*-


如何解决此问题?

一个解决方法可能是使用一个软件包,该软件包尽可能用ASCII表示Unicode:

search_text_unicode=u'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'

search_text_ascii = unidecode(search_text_unicode)
# check the conversion
print(search_text_ascii) # R. Fradique Coutinho, 1332 - Pinheiros, Sao Paulo - SP, 05416-001, Brazil
# got valid ASCII which can be passed to your function
print(build_URL(search_text=search_text_ascii))

返回的URL将在Google Maps API中被识别。

太好了。它可以工作了……这将永远派上用场,因为unicode是人间地狱。的确,很高兴它可以工作!Unidecode作者的所有学分;)