【Python基礎(chǔ)】Python之collections庫(kù)-Counter
一、模塊概述
1、模塊作用
官方說法:collections模塊實(shí)現(xiàn)了特定目標(biāo)的容器,以提供Python標(biāo)準(zhǔn)內(nèi)建容器dict ,list , set , 和tuple的替代選擇。
通俗說法:Python內(nèi)置的數(shù)據(jù)類型和方法,collections模塊在這些內(nèi)置類型的基礎(chǔ)提供了額外的高性能數(shù)據(jù)類型,比如最常用的統(tǒng)計(jì)詞頻most_common()函數(shù),又如基礎(chǔ)的字典是不支持順序的,collections模塊的OrderedDict類構(gòu)建的字典可以支持順序,collections模塊的這些擴(kuò)展的類用處非常大,熟練掌握該模塊,可以大大簡(jiǎn)化Python代碼,提高Python代碼逼格和效率,高手入門必備。
?
2、模塊資料
關(guān)于該模塊,官方的參考資料寫的非常詳細(xì),也很有價(jià)值,大家可以參考
中文文檔: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個(gè)
import collectionsprint(collections.__all__)['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList','UserString', 'Counter', 'OrderedDict', 'ChainMap']
?
這個(gè)模塊實(shí)現(xiàn)了特定目標(biāo)的容器,以提供Python標(biāo)準(zhǔn)內(nèi)建容器dict , list , set , 和tuple 的替代選擇。
namedtuple() | 創(chuàng)建命名元組子類,生成可以使用名字來訪問元素內(nèi)容的tuple子類 |
deque | 類似列表(list)的容器,實(shí)現(xiàn)了在兩端快速添加(append)和彈出(pop) |
ChainMap | 類似字典(dict)的容器類,將多個(gè)映射集合到一個(gè)視圖里面 |
Counter | 字典的子類,提供了可哈希對(duì)象的計(jì)數(shù)功能 |
OrderedDict | 字典的子類,保存了他們被添加的順序,有序字典 |
defaultdict | 字典的子類,提供了一個(gè)工廠函數(shù),為字典查詢提供一個(gè)默認(rèn)值 |
UserDict | 封裝了字典對(duì)象,簡(jiǎn)化了字典子類化 |
UserList | 封裝了列表對(duì)象,簡(jiǎn)化了列表子類化 |
UserString | 封裝了字符串對(duì)象,簡(jiǎn)化了字符串子類化(中文版翻譯有誤) |
?
二、計(jì)數(shù)器-Counter
一個(gè)計(jì)數(shù)器工具提供快速和方便的計(jì)數(shù),Counter是一個(gè)dict的子類,用于計(jì)數(shù)可哈希對(duì)象。它是一個(gè)集合,元素像字典鍵(key)一樣存儲(chǔ),它們的計(jì)數(shù)存儲(chǔ)為值。計(jì)數(shù)可以是任何整數(shù)值,包括0和負(fù)數(shù),Counter類有點(diǎn)像其他語言中的bags或multisets。簡(jiǎn)單說,就是可以統(tǒng)計(jì)計(jì)數(shù),來幾個(gè)例子看看就清楚了,比如
計(jì)算top10的單詞
from collections import Counterimport retext = '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)]#計(jì)算列表中單詞的個(gè)數(shù)cnt = Counter()for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:cnt[word] += 1cntCounter({'red': 2, 'blue': 3, 'green': 1})#上述這樣計(jì)算有點(diǎn)嘛,下面的方法更簡(jiǎn)單,直接計(jì)算就行L = ['red', 'blue', 'red', 'green', 'blue', 'blue']Counter(L)Counter({'red': 2, 'blue': 3, 'green': 1})
from?collections?import?Counter#字符串計(jì)數(shù)Counter('gallahad')Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})#字典計(jì)數(shù)Counter({'red': 4, 'blue': 2})Counter({'red': 4, 'blue': 2})#是個(gè)啥玩意計(jì)數(shù)Counter(cats=4, dogs=8)Counter({'cats': 4, 'dogs': 8})Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])Counter({'red': 2, 'blue': 3, 'green': 1})
計(jì)數(shù)器對(duì)象除了字典方法以外,還提供了三個(gè)其他的方法:
1、elements()
描述:返回一個(gè)迭代器,其中每個(gè)元素將重復(fù)出現(xiàn)計(jì)數(shù)值所指定次。元素會(huì)按首次出現(xiàn)的順序返回。如果一個(gè)元素的計(jì)數(shù)值小于1,elements()?將會(huì)忽略它。
語法:elements( ?)
參數(shù):無
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()
返回一個(gè)列表,其中包含n個(gè)最常見的元素及出現(xiàn)次數(shù),按常見程度由高到低排序。如果 n 被省略或?yàn)镹one,most_common()?將返回計(jì)數(shù)器中的所有元素,計(jì)數(shù)值相等的元素按首次出現(xiàn)的順序排序:
經(jīng)常用來計(jì)算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()
從迭代對(duì)象或映射對(duì)象減去元素。像dict.update()?但是是減去,而不是替換。輸入和輸出都可以是0或者負(fù)數(shù)。
c = Counter(a=4, b=2, c=0, d=-2)d = Counter(a=1, b=2, c=3, d=4)c.subtract(d)cCounter({'a': 3, 'b': 0, 'c': -3, 'd': -6})#減去一個(gè)abcdstr0 = Counter('aabbccdde')str0Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 1})str0.subtract('abcd')str0Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}
?
4、字典方法
通常字典方法都可用于Counter對(duì)象,除了有兩個(gè)方法工作方式與字典并不相同。
fromkeys(iterable)
這個(gè)類方法沒有在Counter中實(shí)現(xiàn)。
update([iterable-or-mapping])
從?迭代對(duì)象?計(jì)數(shù)元素或者 從另一個(gè)?映射對(duì)象?(或計(jì)數(shù)器) 添加。像 dict.update()?但是是加上,而不是替換。另外,迭代對(duì)象應(yīng)該是序列元素,而不是一個(gè)?(key, value)?對(duì)。
sum(c.values()) # total of all countsc.clear() # reset all countslist(c) # list unique elementsset(c) # convert to a setdict(c) # convert to a regular dictionaryc.items() # convert to a list of (elem, cnt) pairsCounter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairsc.most_common()[:-n-1:-1] # n least common elements+c # remove zero and negative counts
?
5、數(shù)學(xué)操作
這個(gè)功能非常強(qiáng)大,提供了幾個(gè)數(shù)學(xué)操作,可以結(jié)合 Counter 對(duì)象,以生產(chǎn) multisets (計(jì)數(shù)器中大于0的元素)。加和減,結(jié)合計(jì)數(shù)器,通過加上或者減去元素的相應(yīng)計(jì)數(shù)。交集和并集返回相應(yīng)計(jì)數(shù)的最小或最大值。每種操作都可以接受帶符號(hào)的計(jì)數(shù),但是輸出會(huì)忽略掉結(jié)果為零或者小于零的計(jì)數(shù)。
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})
單目加和減(一元操作符)意思是從空計(jì)數(shù)器加或者減去。
c = Counter(a=2, b=-4)+cCounter({'a': 2})-cCounter({'b': 4})
?
寫一個(gè)計(jì)算文本相似的算法,加權(quán)相似
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 | collect1sim = float(sum(jiao.values()))/float(sum(bing.values()))return(sim)str_0 = '定位手機(jī)定位汽車定位GPS定位人定位位置查詢'str_1 = '導(dǎo)航定位手機(jī)定位汽車定位GPS定位人定位位置查詢'str_sim(str_0,str_1,5)0.75
?
?
往期精彩回顧
獲取本站知識(shí)星球優(yōu)惠券,復(fù)制鏈接直接打開:
https://t.zsxq.com/qFiUFMV
本站qq群704220115。
加入微信群請(qǐng)掃碼:
