使用高德api匹配地址

2020-07-26  本文已影响0人  michaelxwang
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 26 11:47:58 2020

@author: michaelxwang
"""
import requests
import json
import pandas as pd


key ='你的key值'
cwd ='./data.csv'


def request_url_get(url):
    """ 请求url方法get方法 """
    try:
        r = requests.get(url=url, timeout=30)
        if r.status_code == 200:
            return r.text
        return None
    except:
        print('请求url返回错误异常')
        return None
    
    
def parse_json(content_json):
    """  解析json函数 """
    result_json = json.loads(content_json)
    return result_json

def request_api(url):
    """ 请求高德api 解析json """
    result = request_url_get(url)
    result_json = parse_json(result)
    return result_json

def run():
    """ 运行函数 """
    loc = pd.read_table(cwd,sep = ',', encoding = 'utf-8')
    length = len(loc['物流地址'])
    region = pd.DataFrame()

    for i,location_str in enumerate(loc['物流地址']):
        print(i,'/',length,location_str)
        index_url = f'https://restapi.amap.com/v3/geocode/geo?address={location_str}&key={key}'
        index_result = request_api(index_url)
        df =pd.DataFrame(index_result['geocodes'])
        df['物流地址']=location_str
        region = region.append(df, ignore_index=True,sort=True)

    region.to_csv('loc_with_region.csv',sep='|',index=False,quoting=1,encoding = 'GB18030')

if __name__ == '__main__':
    run()
    


上一篇下一篇

猜你喜欢

热点阅读