2012-05-27 53 views
0
import csv 
from geopy import geocoders 

g = geocoders.Google() 

spamReader = csv.reader(open('locations.csv', 'rb'), delimiter='\t', quotechar='|') 

for row in spamReader: 
    a = ', '.join(row) 
    #print a 
    place, (lat, lng) = g.geocode(a, exactly_one=False) 
    print "%s: %.5f, %.5f" % (place, lat, lng) 

裏面的數據locations.csv樣子:值過多拆封使用Python CSV閱讀器和Geopy

6943  Australia 
6944  Australia 
6945  Australia 
6946  Australia 
6947  Australia 
6951  Australia 

出於某種原因,我留下了一個「值過多解壓」的錯誤。如果我使用註釋的打印語句,這些值會打印出來。有誰知道爲什麼會發生這種情況?

回答

1

問題出在g.geocodeexactly_one參數。當我在shell中運行此我得到:

>>> g.geocode('6943, Australia', exactly_one=False) 
[(u'Australia 6943, Villafontana, Tijuana Municipality, Baja California, Mexico', 
    (32.4988788, -116.8620506)), 
(u'Australia 6943, Castelar, Buenos Aires Province, Argentina', 
    (-34.7036339, -58.6423071)), 
(u'Australia 6943, Rosario, Santa Fe Province, Argentina', 
    (-32.9913482, -60.6398934)), 
(u'Australia, Lebanon', (33.8879118, 35.4749439)), 
(u'Australia, Juliaca, Peru', (-15.4897806, -70.146677)), 
(u'Australia, Lima District 15007, Peru', (-12.0397296, -76.9944836)), 
(u'Australia, Manila, Philippines', (14.48538, 121.0394822)), 
(u'Australia, Conchal\xed, Santiago Metropolitan Region, Chile', 
    (-33.3929606, -70.6780826)), 
(u'Australia, Chiguayante, Biob\xedo Region, Chile', 
    (-36.9556346, -73.0145556)), 
(u'Australia, Copiap\xf3, Atacama Region, Chile', (-27.3978776, -70.2934656))] 

現在,你想分手是大名單逼到place, (lat, lng),當它實際上是人的名單;有too many values在該列表中to unpack逼到兩個(place(lat, lng)),因爲實際上有10.你可以做類似

for place, (lat, lng) in g.geocode(a, exactly_one=False): 
    print place, lat, lng 

或做一些其他類型的列表操作或什麼的。

1

g.geocode()返回一個列表的嵌套元組(place, (lat, lng))。只需使用列表理解壓扁它在單級的列表元組(place, lat, lng)爲 更容易操作是這樣的:

data = ((place, lat, lng) for place, (lat, lng) in g.geocode(a, exactly_one=False)) 
print "\n".join("%s: %.5f, %.5f" % t for t in data)