2015-03-03 95 views
1

我試圖從Google Maps JavaScript API v3使用熱圖可視化服務。CSV字段導入格式問題

我有一個帶有lat,lng和weight的csv文件。它看起來像這樣:

lat, lng, weight 
37.782551, -122.445368, 1 
51.520027, -0.0923842, 2 

我希望得到來自這些CSV值 -

{location: new google.maps.LatLng(37.782551,-122.445368), weight: 1}, 
{location: new google.maps.LatLng(51.520027,-0.0923842), weight: 2}, 

我沒有JavaScript的知識以下結果,所以我嘗試使用Python。

with open('./Test.csv', 'rU') as csvfile: 
    reader = csv.DictReader(csvfile) 
    location = ['{lat},{lng}'.format(**row) for row in reader] 
    weight = ['weight'.format(**row) for row in reader] 

for i in range(0,(len(location))): 
    location_lt = ("new google.mapsLatLng", location[i]) 
    location_we = (location_lt, "weight", weight) 
    print(location_we) 

但是,這有很多問題。重量字段丟失。我相信我應該嘗試使用zip功能。格式也不如上

(('new google.mapsLatLng', '51.5195078,-0.0971911'), 'weight', []) 
(('new google.mapsLatLng', '51.520027,-0.0923842'), 'weight', []) 

任何指針將不勝感激。

回答

1

這裏是我的解決方案 - 它提供完全按照您要求的字符串 - 除了最後一行沒有最後一個逗號,因爲它似乎並不可取。

與其他答案的概念相似,因爲您希望對每一行進行轉換,但我在此直接使用字符串格式來生成結果。

import csv 

class CsvImport(): 
    resultFormat = "{{location: new google.maps.LatLng({lat},{lng}), weight: {weight}}}" 

    def Run(self, filename): 
     # Get the formatted rows from CSV file 
     rows = self.readCsv(filename) 
     print ",\n".join(rows) 

    def readCsv(self, fileName): 
     with open(fileName, 'rU') as csvfile: 
      reader = csv.DictReader(csvfile) 
      # Keys may or may not be pulled in with extra space by DictReader() 
      # The next line simply creates a small dict of stripped keys to original padded keys 
      keys = { key.strip(): key for (key) in reader.fieldnames } 
      # Format each row into the final string 
      rows = [ self.makeRow(row, keys) for row in reader ] 
      return rows; 

    def makeRow(self, row, keys): 
     # Account for extra spaces in keys 
     return self.resultFormat.format(
      lat=row[keys["lat"]].strip(), 
      lng = row[keys["lng"]].strip(), 
      weight=row[keys["weight"]].strip() 
     ) 

if __name__ == "__main__": 
    CsvImport().Run("./Test.csv") 

結果:

enter image description here

+1

偉大的解決方案,甚至更好的解釋,謝謝! – LearningSlowly 2015-03-04 08:42:18

+0

謝謝!很高興它是有幫助的! – 2015-03-04 15:00:42

2

讓我們認真對待您想要的位置的字符串,如您的問題所述。那麼真正的潛在問題就是,您將如何轉換您的CSV文件?你將以相同的方式轉換每一行,所以你應該爲此創建一個函數。例如:

import csv 

fmt01 = "new google.mapsLatLng({lat},{lng})" 
def row_transform01(row): 
    lat = row["lat"] 
    lng = row["lng"] 
    weight = int(row["weight"]) 
    return dict(location=fmt01.format(lat=lat,lng=lng) 
      ,weight=weight 
      ) 

def transform(csvfilename, row_transform): 
    with open(csvfilename, 'rU') as csvfile: 
    reader = csv.DictReader(csvfile) 
    transform = list(row_transform(row) for row in reader) 
    return transform 

for row in transform("/temp/temp.csv",row_transform01): 
    print row 

編輯:

OK,看來你想str,我還以爲你想要dict。沒有汗水,只是改變行變換。

fmt02 = "{{location: new google.maps.LatLng({lat},{lng}), weight:{weight}}}," 
def row_transform02(row): 
    lat = row["lat"] 
    lng = row["lng"] 
    weight = int(row["weight"]) 
    return fmt02.format(lat=lat,lng=lng, weight=weight) 

for row in transform("/temp/temp.csv",row_transform02): 
    print row 
+0

謝謝@Alan。我有兩個輕微的問題 - 我錯過了每個記錄末尾的逗號,並且我在''google.mapsLatLng '''{'location':'new google.mapsLatLng(51.5195078,-0.0971911) ','weight':724} 而不是{location:new google.mapsLatLng(51.5195078,-0.0971911),weight:724}, – LearningSlowly 2015-03-03 13:32:51