用Python中的字典來處理索引統(tǒng)計的方法
最近折騰索引引擎以及數(shù)據(jù)統(tǒng)計方面的工作比較多, 與 Python 字典頻繁打交道, 至此整理一份此方面 API 的用法與坑法備案.
索引引擎的基本工作原理便是倒排索引, 即將一個文檔所包含的文字反過來映射至文檔; 這方面算法并沒有太多花樣可言, 為了增加效率, 索引數(shù)據(jù)盡可往內存里面搬, 此法可效王獻之習書法之勢, 只要把十八臺機器內存全部塞滿, 那么基本也就功成名就了. 而基本思路舉個簡單例子, 現(xiàn)在有以下文檔 (分詞已經(jīng)完成) 以及其包含的關鍵詞
doc_a: [word_w, word_x, word_y] doc_b: [word_x, word_z] doc_c: [word_y]
將其變換為
word_w -> [doc_a] word_x -> [doc_a, doc_b] word_y -> [doc_a, doc_c] word_z -> [doc_b]
寫成 Python 代碼, 便是
doc_a = {'id': 'a', 'words': ['word_w', 'word_x', 'word_y']}
doc_b = {'id': 'b', 'words': ['word_x', 'word_z']}
doc_c = {'id': 'c', 'words': ['word_y']}
docs = [doc_a, doc_b, doc_c]
indices = dict()
for doc in docs:
for word in doc['words']:
if word not in indices:
indices[word] = []
indices[word].append(doc['id'])
print indices
不過這里有個小技巧, 就是對于判斷當前詞是否已經(jīng)在索引字典里的分支
if word not in indices: indices[word] = []
可以被 dict 的 setdefault(key, default=None) 接口替換. 此接口的作用是, 如果 key 在字典里, 那么好說, 拿出對應的值來; 否則, 新建此 key , 且設置默認對應值為 default . 但從設計上來說, 我不明白為何 default 有個默認值 None , 看起來并無多大意義, 如果確要使用此接口, 大體都會自帶默認值吧, 如下
for doc in docs:
for word in doc['words']:
indices. setdefault(word, []) .append(doc['id'])
這樣就省掉分支了, 代碼看起來少很多.
不過在某些情況下, setdefault 用起來并不順手: 當 default 值構造很復雜時, 或產(chǎn)生 default 值有副作用時, 以及一個之后會說到的情況; 前兩種情況一言以蔽之, 就是 setdefault 不適用于 default 需要惰性求值的場景. 換言之, 為了兼顧這種需求, setdefault 可能會設計成
def setdefault(self, key, default_factory):
if key not in self:
self[key] = default_factory()
return self[key]
倘若真如此, 那么上面的代碼應改成
for doc in docs:
for word in doc['words']:
indices.setdefault(word, list ).append(doc['id'])
不過實際上有其它替代方案, 這個最后會提到.
如果說上面只是一個能預見但實際上可能根本不會遇到的 API 缺陷, 那么下面這個就略打臉了.
考慮現(xiàn)在要進行詞頻統(tǒng)計, 即一個詞在文章中出現(xiàn)了多少次, 如果直接拿 dict 來寫, 大致是
def word_count(words):
count = dict()
for word in words:
count.setdefault(word, 0) += 1
return count
print word_count(['hiiragi', 'kagami', 'hiiragi', 'tukasa', 'yosimizu', 'kagami'])
當你興致勃勃地跑起上面代碼時, 代碼會以迅雷不及掩臉之勢把異常甩到你鼻尖上 --- 因為出現(xiàn)在 += 操作符左邊的 count.setdefault(word, 0) 在 Python 中不是一個左值. 怎樣, 現(xiàn)在開始念叨 C艸 類型體系的好了吧.
因為 Python 把默認的字面常量 {} 等價于 dict() 就認為 dict 是銀彈的思想是要不得的; Python 里面各種數(shù)據(jù)結構不少, 解決統(tǒng)計問題, 理想的方案是 collections.defaultdict 這個類. 下面的代碼想必看一眼就明白
from collections import defaultdict
doc_a = {'id': 'a', 'words': ['word_w', 'word_x', 'word_y']}
doc_b = {'id': 'b', 'words': ['word_x', 'word_z']}
doc_c = {'id': 'c', 'words': ['word_y']}
docs = [doc_a, doc_b, doc_c]
indices = defaultdict(list)
for doc in docs:
for word in doc['words']:
indices[word].append(doc['id'])
print indices
def word_count(words):
count = defaultdict(int)
for word in words:
count[word] += 1
return count
print word_count(['hiiragi', 'kagami', 'hiiragi', 'tukasa', 'yosimizu', 'kagami'])
完滿解決了之前遇到的那些破事.
此外 collections 里還有個 Counter , 可以粗略認為它是 defaultdict(int) 的擴展.
相關文章
Python數(shù)據(jù)可視化之用Matplotlib繪制常用圖形
Matplotlib能夠繪制折線圖、散點圖、柱狀圖、直方圖、餅圖. 我們需要知道不同的統(tǒng)計圖的意義,以此來決定選擇哪種統(tǒng)計圖來呈現(xiàn)我們的數(shù)據(jù),今天就帶大家詳細了解如何繪制這些常用圖形,需要的朋友可以參考下2021-06-06
Python?socket之TCP通信及下載文件的實現(xiàn)
本文主要介紹了Python?socket之TCP通信及下載文件的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
Python自動化測試pytest中fixtureAPI簡單說明
這篇文章主要為大家介紹了Python自動化測試pytest中fixtureAPI的簡單說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-10-10

