collections.Counterの勉強
collectionsモジュールをちゃんと勉強したい。
今日はcollections.Counter。
この文章には〜という単語がいくつ含まれているか、みたいなのはこれ使った方が楽。
文章のBoW作る時は絶対これ使いたい。
c = collections.Counter(["tomato" , "orange" ,"apple" , "apple" ,"orange"]) #はこうなる Counter({'apple': 2, 'orange': 2, 'tomato': 1}) #dictの拡張なのでdictっぽく使える c["apple"] #=>2 #追加 c.update(["apple" , "orange"]) #=>Counter({'apple': 3, 'orange': 3, 'tomato': 1}) #こうやって作る事もできる c2 = collections.Counter(tomato=3, orange=1) #=> Counter({'tomato': 3, 'orange': 1}) #Counter同士足せる c + c2 #=> Counter({'orange': 4, 'tomato': 4, 'apple': 3}) #普通に足す事も c['tomato'] += 1 #上位 c.most_common(1) #=>[('apple', 3)]