最近公务员朋友发一份excel给我,火急火燎的问我会不会把地址转成坐标,领导说加急做。我甩她以下这篇文章,说,这个你自己看着搞都立马可以。奈何她虽然看懂了里面的中文汉字,还是玩不转。
那咱就帮帮忙,整整。
https://zhuanlan.zhihu.com/p/102276721
在这里插入图片描述

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import requests

# 执行一次高德地图地理编码的查询
# 输入值:locationList -> 地址的序列,currentKey -> 当前使用的Key
# 返回值:resultList -> 查询成功,返回结果坐标的序列
#        -1 -> 执行当前查询时Key的配额用完了
#        -2 -> 执行当前查询出错
def ExcuteSingleQuery(locationList,currentkey):
    # 1-将locationList中的地址连接成高德地图API能够识别的样子
    locationString = ""     # 当前locationList组成的string
    for location in locationList:
        locationString += location + '|'
    # 2-地理编码查询需要的Url
    output = 'json'    # 查询返回的形式
    batch = 'true'     # 是否支持多个查询
    base = 'https://restapi.amap.com/v3/geocode/geo?'    # 地理编码查询Url的头
    currentUrl = base + "output=" + output + "&batch=" + batch + "&address=" + locationString + "&key=" + currentkey
    # 3-提交请求
    response = requests.get(currentUrl)    # 提交请求
    answer = response.json()   # 接收返回
    # 4-解析Json的内容
    resultList = []    # 用来存放地理编码结果的空序列
    if answer['status'] == '1' and answer['info'] == 'OK':
        # 4.1-请求和返回都成功,则进行解析
        tmpList = answer['geocodes']    # 获取所有结果坐标点
        for i in range(0,len(tmpList)):
            try:
                # 解析','分隔的经纬度
                coordString = tmpList[i]['location']
                coordList = coordString.split(',')
                # 放入结果序列
                resultList.append((float(coordList[0]),float(coordList[1])))
            except:
                # 如果发生错误则存入None
                resultList.append(None)
        return resultList
    elif answer['info'] == 'DAILY_QUERY_OVER_LIMIT':
        # 4.2-当前账号的余额用完了,返回-1
        return -1
    else:
        # 4.3-如果发生其他错误则返回-2
        return -2

if __name__ == '__main__':

    data=pd.read_excel('./地址转坐标1.xlsx',sheet_name="Sheet1",index_col=0)

    for i,j in data.iterrows():
        a = list()
        a.append(str(j['名称']).replace(" ",""))
        a.append(str(j['地址']).replace(" ", ""))
        print(a)
        r=ExcuteSingleQuery(locationList=a, currentkey="3579b36b57cc980c680d0d6916xxxxxx")
        print(r)
        if len(r)>0:
            data.loc[i,'坐标-名称']= str(r[0])
            data.loc[i,'坐标-地址'] = str(r[1])
        else :
            data.loc[i,'坐标']=" "
    print(data)
    data.to_csv('./result1.csv',sep="\t")

我应该甩她一份《快速入门python》。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐