分享一個根據csv表格有地名和權重值的時候如何通過python生成百度熱力圖所要求的數據格式

import pandas as pd
import json
import csv
from urllib.request import urlopen, quote
import requests

#獲取城市的地理編碼
def getlnglat(address): 
    url = 'http://api.map.baidu.com/geocoder/v2/'
    output = 'json' 
    ak = '你申請的' 
    add = quote(address) #由於本文城市變量爲中文,爲防止亂碼,先用quote進行編碼 
    uri = url + '?' + 'address=' + add + '&output=' + output + '&ak=' + ak 
    req = urlopen(uri)
    res = req.read().decode() #將其他編碼的字符串解碼成unicode temp = json.loads(res) #對json數據進行解析 return temp
    #print(req)
    temp = json.loads(res) #對json數據進行解析
    print(temp)
    return temp


file = open(r'C:\Users\Administrator\Desktop\高校\point.json','w') #建立json數據文件
with open(r'C:\Users\Administrator\Desktop\高校\university.csv', 'r',encoding='UTF-8') as csvfile: #打開csv 
    reader = csv.reader(csvfile) 
    for line in reader: #讀取csv裏的數據 # 忽略第一行 
        if reader.line_num == 1: #由於第一行爲變量名稱,故忽略掉 
            continue # line是個list,取得所有需要的值 
        b = line[1].strip() #將第一列city讀取出來並清除不需要字符 
        c= line[4].strip()#將第二列price讀取出來並清除不需要字符 
        lng = getlnglat(b)['result']['location']['lng'] #採用構造的函數來獲取經度 
        lat = getlnglat(b)['result']['location']['lat'] #獲取緯度 
        str_temp = '{"count":' + str(b) +',"lat":' + str(lat) + ',"lng":' + str(lng) + ',"count":' + str(c) +'},' 
        print(str_temp) #也可以通過打印出來,把數據copy到百度熱力地圖api的相應位置上 
        file.write(str_temp) #寫入文檔 
file.close() #保存

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章