調用百度API將地名轉為經緯度


最近做一道數據科學競賽題,特征中有城市名和地名,需要轉為經緯度來使用

故用python寫了一個地名轉經緯度的腳本,調用了百度地圖的API,key在百度地圖開放平台上申請

申請key的地方:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

import json
# import urllib#這么用會有問題
from urllib.request import urlopen,quote

def p2l(name):
# 1、設置url和3個參數(輸出格式,key,要翻譯的地址)
url = 'http://api.map.baidu.com/geocoder/v2/'
output = 'json'
ak = 'sXZHPZahdMeK3Gy3uC7ZeRQrVbZDnP1G'
address = quote(name)

# 2、拼接get請求(url?參數1=值1&參數2=值2&參數3=值3)
request = url + '?' + 'address=' + address + '&output=' + output + '&ak=' + ak

# 3、urlopen發送請求,獲得response
response_file = urlopen(request)

# 4、讀取response字符串
response_str = response_file.read().decode()

# 5、str轉json
response_json = json.loads(response_str)
print(response_json)

# 6、讀json,
lat=response_json['result']['location']['lat']
lng=response_json['result']['location']['lng']

return [lat,lng]

name = input()
p2l(name)

測試一下:

免費的,定位精度還是挺高的,給百度點個贊

 

然后調用寫好的函數將特征中的地名轉為經緯度

list_place=list(set(dataframe2.iloc[:,1]))#注意要去重
list_loc=[]
for elem in list_place:
  name='優衣庫'+elem
  print(name)
  list_loc.append(p2l(name))#執行過程中有的地名可能還查不到,會報錯,此時需要手動優化一下用來查詢的字符串
  print(list_loc)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM