1.地址列表
1.txt
上海市普陀區梅川路299-301號 浙江省杭州市拱墅區豐登路305-311號1層 江蘇省南京市鼓樓區碧樹園86號101室 浙江省寧波市江北區范江岸路38弄6號-10號1層商鋪 浙江省寧波市江東區福明路876-880號 浙江省寧波市江北區清湖路8號 上海市普陀區石泉路436-440號底層 浙江省寧波市海曙區民豐街176號~178號(近藍天路)
2.調用百度地圖API,解析經緯度,根據經緯度,獲取城市
以下代碼使用python3
import requests import json with open("1.txt","r", encoding="utf-8") as fr: with open("2.txt", "w", encoding="utf-8") as fw: for line in fr.readlines(): # 去除換行符 line = line.strip('\n').replace('#',' ') # 去除特殊字符 line1 = line.replace('#', ' ').replace('/',' ') # 地址獲取經緯度 baiduUrl = "http://api.map.baidu.com/geocoder/v2/?ak=XXXXXXX&callback=renderOption&address=%s&output=json" % ( line1) req = requests.get(baiduUrl) content = req.text content = content.replace("renderOption&&renderOption(", "") content = content[:-1] baiduAddr = json.loads(content) lng = baiduAddr["result"]["location"]["lng"] lat = baiduAddr["result"]["location"]["lat"] # 經緯度獲取城市 baiduUrl = "http://api.map.baidu.com/geocoder/v2/?ak=XXXXXXX&callback=renderReverse&location=%s,%s&output=json&pois=0" % ( lat, lng) req = requests.get(baiduUrl) content = req.text content = content.replace("renderReverse&&renderReverse(", "") content = content[:-1] baiduAddr = json.loads(content) province = baiduAddr["result"]["addressComponent"]["province"] city = baiduAddr["result"]["addressComponent"]["city"] district = baiduAddr["result"]["addressComponent"]["district"] # 寫入2.txt文件 new_line = line + "|" + str(lng) + "|" + str(lat) + "|" + province + "|" + city + "|" + district fw.write(new_line) fw.write("\n")
3.運行結果:
2.txt
上海市浦東新區棲山路215號-1|121.55412741874005|31.250531111923426|上海市|上海市|浦東新區 江蘇省南京市鼓樓區鳳凰西街222-1|118.7466970802996|32.0465940656867|江蘇省|南京市|鼓樓區 上海市閔行區華林路229弄34號|121.36316671139555|31.143942453000527|上海市|上海市|閔行區 上海市普陀區梅川路299-301號|121.40369575422491|31.244826892994706|上海市|上海市|普陀區 浙江省杭州市拱墅區豐登路305-311號1層|120.15884493257121|30.34473201035828|浙江省|杭州市|拱墅區 江蘇省南京市鼓樓區碧樹園86號101室|118.76505691316264|32.06860445880062|江蘇省|南京市|鼓樓區 浙江省寧波市江北區范江岸路38弄6號-10號1層商鋪|121.54905723315113|29.899196446280598|浙江省|寧波市|江北區 浙江省寧波市江東區福明路876-880號|121.59768721212123|29.862162545362594|浙江省|寧波市|江東區 浙江省寧波市江北區清湖路8號|121.56583297445964|29.899867569052006|浙江省|寧波市|江北區