0

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を使用したことはありませんが、値の合計が返されると思いました。

ありがとう

4

2 に答える 2

1

呼び出すCounter()と、カウンター オブジェクトが作成されます。それに追加するには、そのupdate()メソッドを使用します。おそらく、に格納された Counter オブジェクトを作成しcity_counter、次にループ呼び出しで作成したいようですcity_counter.update([clusters([loc])])

詳細については、ドキュメントを参照してください

于 2012-12-03T17:16:57.857 に答える
1

問題は、毎回新しいものを作成しているCounterため、毎回新しいものが返されることです。ここには 3 つのオプションがあります。

すべての値を一度に取得してから作成するCounter

基本的に、これには都市のリスト全体を一度に取得してから、Counter.

cities = []
while cursor.alive:
    try:
       cities.append(cursor.next())
    except StopIteration:
       break
print collections.Counter(cities.keys())

Counter新しいものごとに更新doc

Counterこれを行うには、最初に作成済みであることを確認してから、updateメソッドを使用するだけです。

city_counter = collections.Counter()
while cursor.alive:
     city_counter.update([clusters[places]])
     # etc.

使うdefaultdict

あなたの状況では、これが最良の選択肢かもしれません。

city_counter = collections.defaultdict(int)
while cursor.alive:
    city_counter[clusters[places]] += 1
    # etc.
于 2012-12-03T17:17:47.173 に答える