首页 > 技术文章 > 调用百度API将地名转为经纬度

zealousness 2018-01-17 16:30 原文

最近做一道数据科学竞赛题,特征中有城市名和地名,需要转为经纬度来使用

故用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)

推荐阅读