【Python基础】Python之collections库-Counter
一、模塊概述
1、模塊作用
官方說法:collections模塊實現了特定目標的容器,以提供Python標準內建容器dict ,list , set , 和tuple的替代選擇。
通俗說法:Python內置的數據類型和方法,collections模塊在這些內置類型的基礎提供了額外的高性能數據類型,比如最常用的統計詞頻most_common()函數,又如基礎的字典是不支持順序的,collections模塊的OrderedDict類構建的字典可以支持順序,collections模塊的這些擴展的類用處非常大,熟練掌握該模塊,可以大大簡化Python代碼,提高Python代碼逼格和效率,高手入門必備。
?
2、模塊資料
關于該模塊,官方的參考資料寫的非常詳細,也很有價值,大家可以參考
中文文檔:https://docs.python.org/zh-cn/3/library/collections.html#module-collections
英文文檔:https://docs.python.org/3/library/collections.html#module-collections
?
3、模塊子類
用collections.__all__查看所有的子類,一共包含9個
import collections print(collections.__all__) ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList','UserString', 'Counter', 'OrderedDict', 'ChainMap']?
這個模塊實現了特定目標的容器,以提供Python標準內建容器dict , list , set , 和tuple 的替代選擇。
namedtuple() | 創建命名元組子類,生成可以使用名字來訪問元素內容的tuple子類 |
deque | 類似列表(list)的容器,實現了在兩端快速添加(append)和彈出(pop) |
ChainMap | 類似字典(dict)的容器類,將多個映射集合到一個視圖里面 |
Counter | 字典的子類,提供了可哈希對象的計數功能 |
OrderedDict | 字典的子類,保存了他們被添加的順序,有序字典 |
defaultdict | 字典的子類,提供了一個工廠函數,為字典查詢提供一個默認值 |
UserDict | 封裝了字典對象,簡化了字典子類化 |
UserList | 封裝了列表對象,簡化了列表子類化 |
UserString | 封裝了字符串對象,簡化了字符串子類化(中文版翻譯有誤) |
?
二、計數器-Counter
一個計數器工具提供快速和方便的計數,Counter是一個dict的子類,用于計數可哈希對象。它是一個集合,元素像字典鍵(key)一樣存儲,它們的計數存儲為值。計數可以是任何整數值,包括0和負數,Counter類有點像其他語言中的bags或multisets。簡單說,就是可以統計計數,來幾個例子看看就清楚了,比如
計算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})元素從一個iterable 被計數或從其他的mapping (or counter)初始化
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})計數器對象除了字典方法以外,還提供了三個其他的方法:
1、elements()
描述:返回一個迭代器,其中每個元素將重復出現計數值所指定次。元素會按首次出現的順序返回。如果一個元素的計數值小于1,elements()?將會忽略它。
語法:elements( ?)
參數:無
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']?
2、most_common()
返回一個列表,其中包含n個最常見的元素及出現次數,按常見程度由高到低排序。如果 n 被省略或為None,most_common()?將返回計數器中的所有元素,計數值相等的元素按首次出現的順序排序:
經常用來計算top詞頻的詞語。
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、subtract()
從迭代對象或映射對象減去元素。像dict.update()?但是是減去,而不是替換。輸入和輸出都可以是0或者負數。
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}?
4、字典方法
通常字典方法都可用于Counter對象,除了有兩個方法工作方式與字典并不相同。
fromkeys(iterable)
這個類方法沒有在Counter中實現。
update([iterable-or-mapping])
從?迭代對象?計數元素或者 從另一個?映射對象?(或計數器) 添加。像 dict.update()?但是是加上,而不是替換。另外,迭代對象應該是序列元素,而不是一個?(key, value)?對。
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-1:-1] # n least common elements +c # remove zero and negative counts?
5、數學操作
這個功能非常強大,提供了幾個數學操作,可以結合 Counter 對象,以生產 multisets (計數器中大于0的元素)。加和減,結合計數器,通過加上或者減去元素的相應計數。交集和并集返回相應計數的最小或最大值。每種操作都可以接受帶符號的計數,但是輸出會忽略掉結果為零或者小于零的計數。
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 # interp: min(c[x], d[x]) Counter({'a': 1, 'b': 1}) c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2})單目加和減(一元操作符)意思是從空計數器加或者減去。
c = Counter(a=2, b=-4) +c Counter({'a': 2}) -c Counter({'b': 4})?
寫一個計算文本相似的算法,加權相似
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 & collect1bing = 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?
?
往期精彩回顧適合初學者入門人工智能的路線及資料下載機器學習及深度學習筆記等資料打印機器學習在線手冊深度學習筆記專輯《統計學習方法》的代碼復現專輯 AI基礎下載機器學習的數學基礎專輯 獲取本站知識星球優惠券,復制鏈接直接打開: https://t.zsxq.com/qFiUFMV 本站qq群704220115。加入微信群請掃碼:總結
以上是生活随笔為你收集整理的【Python基础】Python之collections库-Counter的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么创建具有真实纹理的CG场景岩石?
- 下一篇: 【机器学习基础】kaggle竞赛中数据抽