Python地址转经纬度并写入表格(调用高德API实现)
本段代码是先将需要转换经纬度的地址存取在 ‘地址.csv’ 文件里,文件截图示例:
代码展示
# coding=utf-8
# SPL
# 时间:2020/12/20 21:15
import csv
import requests
import json
import pandas as pd
import re
num=0
y=[]
'''
在url里key后面的******换为高德开放平台自己申请的key
'''
with open("地址.csv", 'r') as f: #写入将要转换的地址的文件路径,此处为默认文件路径(要先将文件提前导入)(注意是csv格式文件)
r = csv.reader(f, delimiter=',')
for row in r:
print(row[0])
url = "http://restapi.amap.com/v3/geocode/geo?key=******&address=" + row[0]
dat = {
'count': "1",
}
r = requests.post(url, data=json.dumps(dat))
s = r.json()
try:
b = s['geocodes']
text = str(b)
print(text)
except:
text = 'none'
# 省份
try:
pat1 = "'province': '(.*?)',"
province = re.compile(pat1).findall(text)[0]
print("省份:",province)
except:
province = 'none'
print("省份:",province)
# 城市
try:
pat2 = "'city': '(.*?)',"
city = re.compile(pat2).findall(text)[0]
print("城市:",city)
except:
city = 'none'
print("城市:",city)
# 区划
try:
pat3 = "'district': '(.*?)',"
district = re.compile(pat3).findall(text)[0]
print("区划:",district)
except:
district = 'none'
print("区划:",district)
# 经纬度
try:
pat4 = "'location': '(.*?)',"
res3 = re.compile(pat4).findall(text)[0]
# print(res3)
lon_lat = res3.split(',')
lon = float(lon_lat[0])
lat = float(lon_lat[1])
print("经度:",lon)
print("纬度:",lat)
except:
lon = 'none'
lat = 'none'
print("经度:",lon)
print("纬度:",lat)
num += 1
print("第" + str(num) + "条地址转换成功")
print('**************************************')
y.append([num, row[0], province, city, district, lon, lat])
result = pd.DataFrame(y)
result.columns = ['num', 'address', 'province', 'city', 'district', 'lon', 'lat']
result.to_csv('result.csv', encoding='utf-8-sig', index=False)
print("全部地址转换成功")
运行结果
转换成功后生成的表格截图
均为原创,转载请说明出处