python collections模塊

python collections提供了一些數據類型的擴展,使用起來非常方便

Counter類

Counter類是一個計數器類,繼承於字典類,表示對象和相應的計數
常見的一個應用就是詞頻的統計

from collection import Counter
import re


if __name__ == "__main__":
    path = "/usr/lib/python3.5/LICENSE.txt"
    words = re.findall("\w+", open(path).read().lower())
    # most_common(n=None) 返回頻率最高的前n個組成的字典
    print(Counter(words).most_common(10))

[(‘the’, 80), (‘or’, 78), (‘1’, 66), (‘of’, 61), (‘to’, 50), (‘and’, 48), (‘python’, 46), (‘in’, 38), (‘any’, 37), (‘license’, 37)]

OrderedDict類

默認的字典是以Hash表存儲的,進行迭代遍歷的時候,沒有順序性。collection.OrderedDict類提供了可以順序遍歷的字典

from collections import OrderedDict

d = OrderedDict()  # 建立一個OrderedDict對象
d["name"] = "hui"
d["age"] = 20
d["gender"] = "M"
for k, v in d.items():
    print("{}: {}".format(str(k), str(v)))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章