collections.counterメソッドを使用して、各キーの値の数をカウントしようとしています。したがって、データベースを反復処理しているときに、値が見つかった回数のカウントを保持する必要があります。代わりに、DBで発生するたびに値を出力するだけです。これは私が使用する関数のコードです:
def clusters(tweetLocation):
cityCount=None
cities = {"London":[51.50722, -0.12750], "New York":[-74.006605 ,40.714623]}
for k,v in cities.items():
if distance.distance(v, tweetLocation).miles < 50:
cityCount=k
else:
pass
return cityCount
スクリプトのコード:
city_counter=[]
while cursor.alive:#cursor reads all relevant values from the DB
try:
doc = cursor.next()
if not doc['coordinates']:
placeName = doc['place']['full_name']
loc = g.geocode(placeName)
time.sleep(0.15)
city_counter=Counter([clusters([loc])])
else:
places = doc['coordinates']['coordinates']
city_counter=Counter([clusters([places])])
except (ValueError, geocoders.google.GQueryError):
pass
except StopIteration:
break
print city_counter
つまり、次のようなものを返すということです。
Counter({New York: 25, London: 15})
私は得る:
Counter({None: 1})
Counter({None: 1})
Counter({New York: 1})
Counter({None: 1})
......
これまでcollections.counterを使用したことはありませんが、値の合計が返されると思いました。
ありがとう