1. はじめに
カウンター ツールは高速で便利なカウントを提供します。カウンターは dict のサブクラスであり、ハッシュ可能なオブジェクトをカウントするために使用されます。これは、辞書キーのように格納された要素とその数を値として含むコレクションです。カウントには、0 や負の数を含む任意の整数値を指定できます。Counter クラスは、他の言語のバッグやマルチセットに似ています。簡単に言うと統計的に数えることができるので、いくつか例を見てみましょう。
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #计算top10的单词
from collections import Counter
import re
text = 'remove an existing key one level down remove an existing key one level down'
words = re.findall(r'\w+', text)
Counter(words).most_common(10)
[('remove', 2),('an', 2),('existing', 2),('key', 2),('one', 2)('level', 2),('down', 2)]
#计算列表中单词的个数
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
cnt
Counter({'red': 2, 'blue': 3, 'green': 1})
#上述这样计算有点嘛,下面的方法更简单,直接计算就行
L = ['red', 'blue', 'red', 'green', 'blue', 'blue']
Counter(L)
Counter({'red': 2, 'blue': 3, 'green': 1}
|
ログイン後にコピー
要素は反復可能からカウントされるか、他のマッピング (またはカウンター) から初期化されます:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | from collections import Counter
#字符串计数
Counter('gallahad')
Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})
#字典计数
Counter({'red': 4, 'blue': 2})
Counter({'red': 4, 'blue': 2})
#计数
Counter(cats=4, dogs=8)
Counter({'cats': 4, 'dogs': 8})
Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
Counter({'red': 2, 'blue': 3, 'green': 1})
|
ログイン後にコピー
2. 基本操作
1. 統計"反復可能なシーケンス内の各要素の出現数"
1.1 リスト/文字列への影響
次の 2 つの使用方法があります。1 つは直接使用する方法、もう 1 つはインスタンス化する方法です。頻繁に呼び出したい場合は、Counter のさまざまなメソッドを簡単に呼び出すことができ、同じルーチンが他の反復可能なシーケンスに使用されるため、明らかに後者の方が簡潔です。
1 2 3 4 5 6 7 8 9 10 | #首先引入该方法
from collections import Counter
#对列表作用
list_01 = [1,9,9,5,0,8,0,9] #GNZ48-陈珂生日
print (Counter(list_01)) #Counter({9: 3, 0: 2, 1: 1, 5: 1, 8: 1})
#对字符串作用
temp = Counter('abcdeabcdabcaba')
print (temp) #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
#以上其实是两种使用方法,一种是直接用,一种是实例化以后使用,如果要频繁调用的话,显然后一种更简洁
|
ログイン後にコピー
1.2 結果の出力
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #查看类型
print ( type(temp) ) #< class 'collections.Counter'>
#转换为字典后输出
print ( dict(temp) ) #{'b': 4, 'a': 5, 'c': 3, 'd': 2, 'e': 1}
for num, count in enumerate(dict(temp).items()):
print ( count )
"" "
('e', 1)
('c', 3)
('a', 5)
('b', 4)
('d', 2)
"" "
|
ログイン後にコピー
1.3 組み込みの items() メソッドを使用して出力
この方法は、辞書に変換して出力するよりも明らかに便利です。 :
1 2 3 4 5 6 7 8 9 10 11 | print (temp.items()) #dict_items([('e', 1), ('c', 3), ('b', 4), ('d', 2), ('a', 5)])
for item in temp.items():
print (item)
"" "
('a', 5)
('c', 3)
('d', 2)
('e', 1)
('b', 4)
"" "
|
ログイン後にコピー
2. most_common() は、最も多く出現する要素をカウントします
most_common() メソッドを使用して、n 個の最も一般的な要素と出現数を順番に含むリストを返します。一般性の低い順に並べ替えます。 n が省略されている場合、または None の場合、most_common() はカウンター内のすべての要素を返します。等しいカウント値を持つ要素は、最初に出現した順にソートされます。上位の単語頻度を計算するためによく使用される単語:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #求序列中出现次数最多的元素
from collections import Counter
list_01 = [1,9,9,5,0,8,0,9]
temp = Counter(list_01)
#统计出现次数最多的一个元素
print (temp.most_common(1)) #[(9, 3)] 元素“9”出现3次。
print (temp.most_common(2)) #[(9, 3), (0, 2)] 统计出现次数最多个两个元素
#没有指定个数,就列出全部
print (temp.most_common()) #[(9, 3), (0, 2), (1, 1), (5, 1), (8, 1)]
|
ログイン後にコピー
1 2 3 4 5 | Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
Counter('abracadabra').most_common(5)
[('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
|
ログイン後にコピー
3. elements() および sort() メソッド
説明: 各要素がカウント値で指定された回数だけ繰り返される反復子を返します。要素は最初に出現した順に返されます。要素の数が 1 未満の場合、elements() はそれを無視します。
例:
1 2 3 4 5 6 7 8 9 10 | c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
c = Counter(a=4, b=2, c=0, d=5)
list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b', 'd', 'd', 'd', 'd', 'd']
|
ログイン後にコピー
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from collections import Counter
c = Counter('ABCABCCC')
print (c.elements()) #<itertools.chain object at 0x0000027D94126860>
#尝试转换为list
print (list(c.elements())) #['A', 'A', 'C', 'C', 'C', 'C', 'B', 'B']
#或者这种方式
print (sorted(c.elements())) #['A', 'A', 'B', 'B', 'C', 'C', 'C', 'C']
#这里与sorted的作用是: list all unique elements,列出所有唯一元素
#例如
print ( sorted(c) ) #['A', 'B', 'C']
|
ログイン後にコピー
公式ドキュメントの例:
1 2 3 4 5 6 7 | # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
prime_factors = Counter({2: 2, 3: 3, 17: 1})
product = 1
for factor in prime_factors.elements(): # loop over factors
product *= factor # and multiply them
print (product) #1836
#1836 = 2*2*3*3*3*17
|
ログイン後にコピー
4.subtract() 減算演算: 出力は、結果が 0 または 0 未満であるカウントを無視しません
反復可能なオブジェクトまたはマップされたオブジェクトから要素を減算します。入力と出力は両方とも 0 または負の値にすることができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
#减去一个abcd
str0 = Counter('aabbccdde')
str0
Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 1})
str0.subtract('abcd')
str0
Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}
|
ログイン後にコピー
1 2 3 | subtract_test01 = Counter( "AAB" )
subtract_test01.subtract( "BCC" )
print (subtract_test01) #Counter({'A': 2, 'B': 0, 'C': -2})
|
ログイン後にコピー
ここでのカウントはゼロに減らすことができ、ゼロと負の数を含めることができます:
1 2 3 4 5 6 7 | subtract_test02 = Counter( "which" )
subtract_test02.subtract( "witch" ) #从另一个迭代序列中减去元素
subtract_test02.subtract(Counter( "watch" )) #^……
#查看结果
print ( subtract_test02[ "h" ] ) # 0 ,whirch 中两个,减去witch中一个,减去watch中一个,剩0个
print ( subtract_test02[ "w" ] ) #-1
|
ログイン後にコピー
5. ディクショナリ メソッド
通常、ディクショナリ メソッドは Counter オブジェクトに使用できます。ただし、辞書とは異なる動作をするメソッドが 2 つあります。
1 2 3 4 5 6 7 8 9 | sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common(n) # n least common elements
+c # remove zero and negative counts
|
ログイン後にコピー
6. 数学的演算
この関数は非常に強力で、Counter オブジェクトと組み合わせてマルチセット (0 より大きい要素) を生成できるいくつかの数学的演算を提供します。カウンター )。加算と減算では、対応する要素の数を加算または減算してカウンターを結合します。 Intersection と Union は、対応するカウントの最小値または最大値を返します。各操作は符号付きカウントを受け入れますが、出力では結果が 0 または 0 未満のカウントは無視されます。
1 2 3 4 5 6 7 8 9 10 | c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
c - d # subtract (keeping only positive counts)
Counter({'a': 2})
c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
c | d # union: max(c[x], d[x])
Counter({'a': 3, 'b': 2})
|
ログイン後にコピー
1 2 3 4 | print (Counter('AAB') + Counter('BCC'))
#Counter({'B': 2, 'C': 2, 'A': 2})
print (Counter( "AAB" )-Counter( "BCC" ))
#Counter({'A': 2})
|
ログイン後にコピー
And" および "OR" 演算:
1 2 3 4 5 | print (Counter('AAB') & Counter('BBCC'))
#Counter({'B': 1})
print (Counter('AAB') | Counter('BBCC'))
#Counter({'A': 2, 'C': 2, 'B': 2})
|
ログイン後にコピー
一方向加算および減算 (単項演算子) は、空のカウンタに加算または減算することを意味します。これは、カウント値に正の値を乗算することと同等です。または負の値の場合、出力では、結果が 0 または 0 未満であるカウントも無視されます:
1 2 3 4 5 | c = Counter(a=2, b=-4)
+c
Counter({'a': 2})
-c
Counter({'b': 4})
|
ログイン後にコピー
テキストの類似性、重み付けされた類似性を計算するアルゴリズムを作成します:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def str_sim(str_0,str_1,topn):
topn = int(topn)
collect0 = Counter(dict(Counter(str_0).most_common(topn)))
collect1 = Counter(dict(Counter(str_1).most_common(topn)))
jiao = collect0 & collect1
bing = collect0 | collect1
sim = float(sum(jiao.values()))/float(sum(bing.values()))
return (sim)
str_0 = '定位手机定位汽车定位GPS定位人定位位置查询'
str_1 = '导航定位手机定位汽车定位GPS定位人定位位置查询'
str_sim(str_0,str_1,5)
0.75
|
ログイン後にコピー
7. 合計を計算します。要素の数、Keys() および Values()
1 2 3 4 5 6 7 | from collections import Counter
c = Counter('ABCABCCC')
print (sum(c.values())) # 8 total of all counts
print (c.keys()) #dict_keys(['A', 'B', 'C'])
print (c.values()) #dict_values([2, 2, 4])
|
ログイン後にコピー
8. 単一要素の結果のクエリ
1 2 3 4 | from collections import Counter
c = Counter('ABBCC')
#查询具体某个元素的个数
print (c[ "A" ]) #1
|
ログイン後にコピー
9. Add
1 2 3 4 | for elem in 'ADD': # update counts from an iterabl
c[elem] += 1
print (c.most_common()) #[('C', 2), ('D', 2), ('A', 2), ('B', 2)]
#可以看出“A”增加了一个,新增了两个“D”
|
ログイン後にコピー
10. 削除 (del)
1 2 3 4 | del c[ "D" ]
print (c.most_common()) #[('C', 2), ('A', 2), ('B', 2)]
del c[ "C" ]
print (c.most_common()) #[('A', 2), ('B', 2)]
|
ログイン後にコピー
11. update update()
1 2 3 | d = Counter( "CCDD" )
c.update(d)
print (c.most_common()) #[('B', 2), ('A', 2), ('C', 2), ('D', 2)]
|
ログイン後にコピー
12. Clear Clear()
1 2 | c.clear()
print (c) #Counter()
|
ログイン後にコピー
3. Summary
Counter は dict のサブクラスで、主にアクセスするために使用されます。オブジェクトの頻度がカウントされます。
一般的に使用されるメソッド:
elements(): オブジェクトの数がカウントされている場合、各要素の反復計算回数である反復子を返します。要素 1 未満の場合は無視されます
most_common([n]): 最も頻繁にアクセスされる n 個の要素とその数を提供するリストを返します
-
subtract([iterable-or-mapping]): 反復可能なオブジェクトから要素を減算します。入力と出力は 0 または負の数値にすることができますが、これはマイナス記号の役割とは異なります -
update ([iterable-or-mapping]): 反復可能オブジェクトから要素をカウントするか、別のマッピング オブジェクト (またはカウンター) から追加します。
例:
1 2 3 4 5 6 7 | # 统计字符出现的次数
>>> import collections
>>> collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 统计单词数
>>> collections.Counter('hello world hello world hello nihao'.split())
Counter({'hello': 3, 'world': 2, 'nihao': 1})
|
ログイン後にコピー
一般的に使用される方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | >>> c = collections.Counter('hello world hello world hello nihao'.split())
>>> c
Counter({'hello': 3, 'world': 2, 'nihao': 1})
# 获取指定对象的访问次数,也可以使用get()方法
>>> c['hello']
3
>>> c = collections.Counter('hello world hello world hello nihao'.split())
# 查看元素
>>> list(c.elements())
['hello', 'hello', 'hello', 'world', 'world', 'nihao']
# 追加对象,或者使用c.update(d)
>>> c = collections.Counter('hello world hello world hello nihao'.split())
>>> d = collections.Counter('hello world'.split())
>>> c
Counter({'hello': 3, 'world': 2, 'nihao': 1})
>>> d
Counter({'hello': 1, 'world': 1})
>>> c + d
Counter({'hello': 4, 'world': 3, 'nihao': 1})
# 减少对象,或者使用c.subtract(d)
>>> c - d
Counter({'hello': 2, 'world': 1, 'nihao': 1})
# 清除
>>> c.clear()
>>> c
Counter()
|
ログイン後にコピー
以上がPython カウンター: collections.Counter の使用方法?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。