Python3实例分享_经纬度转换为地区和地址

Python3实例分享_经纬度转换为地区和地址

说明

创建一个逗号分隔的CSV格式的文件,命名为address.csv
填写经纬度信息
执行代码
结果保存在dis.csv

创建一个csv文件

address.csv

LongitudeLatitude
120.1076835.91555
120.3623136.13871
119.7917335.58356

源代码

import csv
import time
import os
import requests

## 判断字符串是否是小数
def DataCheck():
    starttime = time.time()
    i = 0
    print('数据检查中')
    print('======================================================')
    with open('address.csv') as f:
        reader = csv.reader(f)
        next(f)
        for row in reader:
            longi = row[0]
            lati = row[1]

            if (longi.split(".")[0]).isdigit() and (lati.split(".")[0]).isdigit():
                None
            else:
                print(reader.line_num+1,'行中的(',longi,')(',lati,")格式检查不通过,请修改后再试")
                i=i+1
        print('======================================================')
        print('总计',reader.line_num+1,'行')
        if i == 0:
            print('检查完成,未发现错误')
        else:
            print('检查完成,发现错误', i, '个')
    endtime = time.time()
    print('用时', round(endtime - starttime,2), '秒')
    os.system('pause')

## 纠偏		
## https://lbs.amap.com/api/webservice/guide/api/convert API链接
def recorrect(locationX):#纠偏API函数
    parameters = {'locations': locationX, 'key': 'c5668c9cdc12424a405008a713034dc4','coordsys':'gps'}
    base_url = 'https://restapi.amap.com/v3/assistant/coordinate/convert'
    response = requests.get(url=base_url, params=parameters)
    info_newGPS = response.json()
    return info_newGPS['locations']

def split(lst):#数据按照二十个一组进行处理
    new_lst=[]
    new= [lst[i:i+20] for i in range(0,len(lst),20)]
    i=0
    for i in range(len(new)):
        # print('提取中: {:.0f}%'.format(i / len(new) * 100))
        a="|".join(str(m) for m in new[i])
        new_lst.append(a)
    print('CSV文件读取完成: 100%')
    return new_lst

def DealData(lst): #分列后进行处理查询
    new_lst = split(lst)
    print('每 20 个站点查询并转换一次,一共需要查询',len(new_lst),'次,预计需要',int(len(new_lst)),'秒')
    result_list=[]
    new_result_combine=[]
    for i in range(len(new_lst)):
        print('第',i+1,'次查询中...')
        block1=new_lst[i]
        # print('检查:',block1)
        result=recorrect(block1)
        # print('纠偏经纬度为:',result)
        result_list.append(result)
        #print('最终结果为:',result_list)
        new_result_combine=zip(result_list)
        # print(new_result_combine)
        new_result_list = list(new_result_combine)
        # print('转换结果:',new_result_list)
    return new_result_list

def RecorrectV4():
    starttime = time.time()
    print('高德坐标转换')
    print('======================================================')
    lst=[]
    with open('address.csv') as f:
        reader = csv.reader(f)
        next(f)
        for row in reader:
            longi = row[0]
            lati = row[1]
            location = longi + ',' + lati
            lst.append(location)

    new_result_list = DealData(lst)

    with open('newGPS.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(new_result_list)
    endtime = time.time()
    print('查询完成')
    print('用时', round(endtime - starttime,2), '秒')
    print('纠偏成高德坐标系结果已经保存到newGPS.csv')
    print('======================================================')
    os.system('pause')

##获取地址
def lo_to_addr(location):#经纬度转地址
    parameters = {'location': location, 'key': 'c5668c9cdc12424a405008a713034dc4','batch':'true'}
    base_url = 'https://restapi.amap.com/v3/geocode/regeo'
    response = requests.get(url=base_url, params=parameters)
    info_site = response.json()
    # 地区路径:info_site['regeocode']['addressComponent']['district']
    # 地址路径:info_site['formatted_address']
    return info_site['regeocodes']


def GetAddV4():
    starttime = time.time()

    print('从高德API获取地区中...')
    with open('newGPS.csv') as f:
        reader = csv.reader(f)
        # for row in reader:
        #     # 行号从1开始
        #     print(reader.line_num, row)

        dis_from_location_list = []
        address_from_location_list = []
        longi_list = []
        lati_list = []
        location_list=[]

        for row in reader:
            location = row[0]
            # print(location)
            location=location.replace(';','|')
            result=lo_to_addr(location)

            for num in range(0,20):
                try:
                    DataPart= result[num]
                except IndexError:
                    break
                addre=DataPart['formatted_address']
                dis=DataPart['addressComponent']['district']
                # print('检查:',DataPart)
                # print('地址:',addre)
                # print('地区:', dis)
                address_from_location_list.append(addre)
                dis_from_location_list.append(dis)
        # print(address_from_location_list)
        # print(dis_from_location_list)

        dis_from_location_list.insert(0, '地区')
        address_from_location_list.insert(0, '地址')

    result_combine = zip(dis_from_location_list, address_from_location_list)
    result_list = list(result_combine)
    print('======================================================')
    print('输出结果:\n', result_list)
    print('======================================================')
    with open('dis.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(result_list)
    endtime = time.time()
    print('用时', round(endtime - starttime,2), '秒')
    print('结果已经保存到dis.csv')
    print('======================================================')
    os.system('pause')

#主程序入口	
if __name__ == "__main__":

    DataCheck()
    RecorrectV4()
    GetAddV4()

使用高德“逆地理编码API”从经纬度反推地区,每日调用上限为6000次
API链接:https://lbs.amap.com/api/webservice/guide/api/georegeo/

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值