萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 字典實戰:高效構建倒排索引與詞頻統計

Python 字典(dict)是處理索引統計、詞頻計數等場景的核心利器。本文從倒排索引的基本原理出發,逐步演示如何用字典優雅地解決「文檔→關鍵字」映射與「詞頻統計」兩大經典問題,並深入剖析 setdefault 的坑與 collections.defaultdict、Counter 的最佳實踐。

場景引入:倒排索引的核心邏輯

假設有三份已分詞的文檔:

doc_a: [word_w, word_x, word_y]
doc_b: [word_x, word_z]
doc_c: [word_y]

目標是建立「關鍵字 → 文檔 ID 列表」的倒排索引:

word_w → [doc_a]
word_x → [doc_a, doc_b]
word_y → [doc_a, doc_c]
word_z → [doc_b]

基礎寫法:手動判斷 Key 是否存在

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)

進階技巧:用 setdefault 消除分支

dict.setdefault(key, default) 若 key 存在則回傳其值,否則插入 key 並設為 default 再回傳。可將上述 if 判斷簡化為一行:

for doc in docs:
    for word in doc['words']:
        indices.setdefault(word, []).append(doc['id'])

setdefault 的隱藏陷阱

  • 預設值會即時求值:setdefault(key, []) 每次調用都會建立新列表,即使 key 已存在也會建立再丟棄,效能微損。
  • 不支援惰性求值:若預設值構造昂貴(如大型物件、資料庫連線),無法延遲建立。
  • 無法用於「累加」操作:count.setdefault(word, 0) += 1 會報錯,因為回傳值非左值。

最佳解法:collections.defaultdict

defaultdict(factory) 在 key 缺失時自動呼叫 factory() 產生預設值,完美解決上述問題:

倒排索引版

from collections import defaultdict

indices = defaultdict(list)
for doc in docs:
    for word in doc['words']:
        indices[word].append(doc['id'])

詞頻統計版

def word_count(words):
    count = defaultdict(int)  # int() 回傳 0
    for word in words:
        count[word] += 1
    return count

print(word_count(['hiiragi', 'kagami', 'hiiragi', 'tukasa', 'yosimizu', 'kagami']))
# defaultdict(, {'hiiragi': 2, 'kagami': 2, 'tukasa': 1, 'yosimizu': 1})

補充利器:collections.Counter

專為計數設計,可視為 defaultdict(int) 的增強版,提供 most_common()、算術運算等豐富功能:

from collections import Counter
cnt = Counter(['hiiragi', 'kagami', 'hiiragi'])
print(cnt.most_common(1))  # [('hiiragi', 2)]

總結建議

場景推薦做法
簡單分組、列表聚合defaultdict(list)
計數、頻率統計defaultdict(int) 或 Counter
預設值構造成本高、需惰性求值自定義 defaultdict(lambda: expensive_factory())
舊代碼維護、不想引入額外 importsetdefault(注意左值限制)

善用標準庫 collections,能讓統計類程式碼既簡潔又高效,是 Python 開發者必備的內功心法。

copyright © 萬盛學電腦網 all rights reserved