数据来源 https://github.com/fan-lc/stats_gov
有文本文件内容如下:
湛江市,麻章区,麻章镇,赤岭村委会,440811100220
... ...
for_geolocation.py
# coding=utf-8
from urllib.request import urlopen,quote
import os,sys
import json
import time
if len(sys.argv) ==2:
f1 = sys.argv[1]
else:
print('usage: python for_geolacation.py file1.txt ')
sys.exit(1)
if not os.path.exists(f1):
print('Error: %s not found\n' % f1)
sys.exit(1)
#ak = '你的ak'#需填入自己申请应用后生成的ak
ak='FA8atAaqd1wajikD56lPqtiaNCleCeyz'
url='http://api.map.baidu.com/geocoder/v2/?address='
fp = open(f1,'r')
f2 = f1 +'.geo'
fp2 = open(f2,'w')
aline =''
for line in fp:
t = line.strip().split(',')
cun = t[3].find(u'村')
if cun != -1:
t3 = t[3][0:cun+1]
else:
t3 = t[3]
address = ','.join((t[0],t[1],t[2],t3))
addr = quote(address)
#print(address)
url2 = url+ addr +"&output=json&ak="+ ak
req = urlopen(url2)
res = req.read().decode()
temp = json.loads(res)
lng = temp['result']['location']['lng'] # 获取经度
lat = temp['result']['location']['lat'] # 获取纬度
if lng != None and lat != None:
aline = '{0},{1:.6f},{2:.6f}\n'.format(line.strip(),lng,lat)
fp2.write(aline)
#print(aline)
time.sleep(1)
#
fp.close()
fp2.close()
print(f2)
运行 python for_geolocation.py gd_xzqh.txt