1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| import json import requests
def parse_district(districtObj: dict, idx=1, parent_id=0): res = [] if 'name' in districtObj.keys(): if districtObj['level'] == 'street': return res
lng, lat = districtCenter(districtObj['center']) level = districtLevel(districtObj['level']) citycode = districtObj['citycode'] if isinstance(districtObj['citycode'], str) else ''
# {"citycode":"0379","adcode":"410300","name":"洛阳市","center":"112.434468,34.663041","level":"city"} # idx, districtObj['adcode'], districtObj['name'], level, citycode, lng, lat, parent_id item = { 'id': idx, 'adcode': districtObj['adcode'], 'name': districtObj['name'], 'level': level, 'citycode': citycode, 'lng': lng, 'lat': lat, 'parent_id': parent_id } res.append(item) parent_id = idx idx = idx + 1
if isinstance(districtObj.get('districts'), list) and len(districtObj['districts']) > 0: for subitem in districtObj['districts']: subs = parse_district(subitem, idx, parent_id) res += subs idx += len(subs) return res
def districtLevel(levelStr): map_val = { 'country': 0, 'province': 1, 'city': 2, 'district': 3 } return map_val[levelStr]
def districtCenter(center): items = center.split(',') return float(items[0]), float(items[1])
# 结果保存为json数组 def saveJson(data): with open('area_dict.json', 'w', encoding='utf-8') as fp: json.dump(data, fp, ensure_ascii=False, indent=4) print('Save json file: area_dict.json')
# 保存为SQL脚本 def saveSqlFile(data, includeCreate=True): # +--------------+-------------+------+-----+---------+----------------+ # | Field | Type | Null | Key | Default | Extra | # +--------------+-------------+------+-----+---------+----------------+ # | area_id | int(11) | NO | PRI | NULL | auto_increment | # | area_code | char(6) | NO | MUL | NULL | | # | area_name | varchar(20) | NO | MUL | NULL | | # | level | tinyint(1) | NO | MUL | 0 | | # | city_code | char(4) | YES | | NULL | | # | longitudinal | int(11) | YES | | 0 | | # | lateral | int(11) | YES | | 0 | | # | parent_id | int(11) | NO | MUL | -1 | | # +--------------+-------------+------+-----+---------+----------------+ createCode = """ CREATE TABLE `area_dict` ( `area_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '地区Id', `area_code` char(6) NOT NULL COMMENT '地区编码', `area_name` varchar(20) NOT NULL COMMENT '地区名', `level` tinyint(1) NOT NULL DEFAULT '0' COMMENT '地区级别(1:省份province,2:市city,3:区县district,4:街道street)', `city_code` char(4) DEFAULT NULL COMMENT '城市编码', `lng` int(11) DEFAULT '0' COMMENT '城市中心经度', `lat` int(11) DEFAULT '0' COMMENT '城市中心纬度', `parent_id` int(11) NOT NULL DEFAULT '-1' COMMENT '地区父节点', PRIMARY KEY (`area_id`), KEY `areaCode` (`area_code`), KEY `parentId` (`parent_id`), KEY `level` (`level`), KEY `areaName` (`area_name`) ) ENGINE=InnoDB AUTO_INCREMENT=3261 DEFAULT CHARSET=utf8 COMMENT='地区码表'; """ with open('area_dict.sql', 'w', encoding='utf-8') as fp: if includeCreate: fp.write(createCode) for item in data: item['lng'] = int(item['lng'] * 1e6) item['lat'] = int(item['lat'] * 1e6) sql = "INSERT INTO area_dict(`area_id`,`area_code`,`area_name`,`level`,`city_code`,`lng`,`lat`,`parent_id`) " + \ "VALUES({id},'{adcode}','{name}',{level},'{citycode}',{lng},{lat},{parent_id});\n".format(**item)
fp.write(sql)
print('Save sql file: area_dict.sql')
if __name__ == "__main__": url = 'https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key=[你的高德地图key]'
response = requests.get(url) if response.ok and response.status_code == 200: data = response.json() data = parse_district(data) print('Download data successful, total:{0}!'.format(len(data))) saveJson(data) saveSqlFile(data) else: print('Request error!')
|