我正在尝试使用Google Maps JavaScript API v3中的热图可视化服务。
我有一个带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', [])
任何指针都会非常感激。
答案 0 :(得分: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
修改强>
好的,似乎你想要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
答案 1 :(得分: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")
结果: