1、從一個計數問題開始
初學Python的人很可能會遇到字頻統計這樣的練習題,那麼很容易會想到使用for循環來做,可是for循環的效率是很低的,而且會涉及到嵌套循環,代碼及其冗餘。
比如給定一個字符串,對字母進行計數統計:
Python is a popular programming language
一般會這樣寫:
<code>my_str ="Python is a popular programming language"
def
str_count
(strs)
:'''對字符串進行字頻統計,使用字典的get方法進行判斷'''
str_dict = {}for
iin
strs: str_dict[i] = str_dict.get(i,0
) +1
return
str_dict str_count(my_str)/<code>
輸出:
這次我們來介紹collection模塊中的一個計數方法Counter,用它來計數操作可能只需一行代碼。也由此學習一下Python中的內置模塊-collections及它的強大功能。
如果使用Counter計數器來對上面那段字符串進行字頻統計,就很簡單:
<code>from
collectionsimport
Counter my_str ="Python is a popular programming language"
Counter(my_str)/<code>
輸出:
可以看到Counter計數器使用及其簡單,只需要傳入可迭代對象,就能統計每個元素的出現頻次。
如果要對一篇文章,甚至一部小說進行字頻統計,該怎麼做呢?
以李白詩集為例,任務是統計所有字的頻次,並找出出現頻次最高的十個字。
這裡你不妨先猜猜會有哪些字名列前十,話不多說放代碼:
<code>from
collectionsimport
Counterwith
open('李白.txt'
)as
f: c_list = f.readlines() c_str =','
.join(c_list) c_cnt = Counter(c_str) useless_character = [','
,','
,'。'
,'【'
,'】'
,'\n'
,'李'
,'白'
]for
iin
useless_character:del
c_cnt[i] c_top_10 = c_cnt.most_common(10
) print(c_cnt) print(c_top_10)/<code>
輸出:
出現頻次最高的前十個字:
你猜中了幾個呢?
2、聊聊Counter的其他用法
collections模塊實現了特定目標的容器,來提供Python標準內建容器 dict、list、set、tuple 的替代選擇。
也就是說collections模塊是作為Python內建容器的補充,在很多方面它用起來更加有效率。
Counter是字典的子類,用於計數可哈希對象,計數元素像字典鍵(key)一樣存儲,它們的計數存儲為值。
所以說Counter對象可以使用字典的所有方法。
創建Counter對象
<code>from
collectionsimport
Counter c = Counter() c = Counter('gallahad'
) c = Counter({'red'
:4
,'blue'
:2
}) c = Counter(cats=4
, dogs=8
) /<code>
對可迭代對象進行計數
<code>from
collectionsimport
Counter c = Counter('bananas'
) c # 輸出:Counter({'b'
:1
,'a'
:3
,'n'
:2
,'s'
:1
})/<code>
根據鍵引用值
<code>from
collectionsimport
Counter c = Counter('bananas'
) c['a'
] /<code>
如果不存在該鍵,則返回0
<code>from
collectionsimport
Counter c = Counter('bananas'
) c['u'
] /<code>
刪除其中一個鍵值對
<code>from
collectionsimport
Counter c = Counter('bananas'
) del c['a'
] c # 輸出:Counter({'b'
:1
,'n'
:2
,'s'
:1
})/<code>
用映射來創建一個Counter,並返回迭代器
<code>from
collectionsimport
Counter c = Counter({'red'
:3
,'blue'
:1
,'black'
:2
}) list(c.elements()) # 輸出:['red'
,'red'
,'red'
,'blue'
,'black'
,'black'
]/<code>
查看出現頻次最高的前n元素及其次數
<code>from
collectionsimport
Counter c = Counter('absabasdvdsavssaffsdaws'
) c.most_common(3
) # 輸出:[('s'
,7
), ('a'
,6
), ('d'
,3
)]/<code>
兩個Counter相減
<code>from collectionsimport
Counterc
=Counter
(a=4
, b=2
,c
=0
) d =Counter
(a=1
, b=2
,c
=3
)c
.subtract(d)c
# 輸入:Counter
({'a':3
, 'b':0
, 'c
': -3
})/<code>
轉換成字典
<code>from
collectionsimport
Counter c = Counter('bananas'
) dict(c) # 輸出:{'b'
:1
,'a'
:3
,'n'
:2
,'s'
:1
}/<code>
添加可迭代對象
<code>from
collectionsimport
Counter c = Counter('bananas'
) c.update('apples'
) c # 輸出:Counter({'b'
:1
,'a'
:4
,'n'
:2
,'s'
:2
,'p'
:2
,'l'
:1
,'e'
:1
})/<code>
3、總結
Counter是字典的一個子類,它繼承了字典的所有方法。
Counter作為計數器,使用簡單高效。
鍵代表計數元素,值代表計數值。
most_common()方法用於排序,選取頻次前n的鍵值對。
Counter對象可以進行加減運算及邏輯運算操作。