用Python中的字典來處理索引統計的方法

來源:互聯網
上載者:User

用Python中的字典來處理索引統計的方法

   這篇文章主要介紹了用Python中的字典來處理索引統計的方法,字典的使用是Python學習當中的基礎知識,本文則是相關的一個小實踐,需要的朋友可以參考下

  最近折騰索引引擎以及資料統計方面的工作比較多, 與 Python 字典頻繁打交道, 至此整理一份此方面 API 的用法與坑法備案.

  索引引擎的基本工作原理便是倒排索引, 即將一個文檔所包含的文字反過來映射至文檔; 這方面演算法並沒有太多花樣可言, 為了增加效率, 索引資料盡可往記憶體裡面搬, 此法可效王獻之習書法之勢, 只要把十八台機器記憶體全部塞滿, 那麼基本也就功成名就了. 而基本思路舉個簡單例子, 現在有以下文檔 (分詞已經完成) 以及其包含的關鍵詞

  ?

1

2

3

doc_a: [word_w, word_x, word_y]

doc_b: [word_x, word_z]

doc_c: [word_y]

  將其變換為

  ?

1

2

3

4

word_w -> [doc_a]

word_x -> [doc_a, doc_b]

word_y -> [doc_a, doc_c]

word_z -> [doc_b]

  寫成 Python 代碼, 便是

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

  不過這裡有個小技巧, 就是對於判斷當前詞是否已經在索引字典裡的分支

  ?

1

2

if word not in indices:

indices[word] = []

  可以被 dict 的 setdefault(key, default=None) 介面替換. 此介面的作用是, 如果 key 在字典裡, 那麼好說, 拿出對應的值來; 否則, 建立此 key , 且設定預設對應值為 default . 但從設計上來說, 我不明白為何 default 有個預設值 None , 看起來並無多大意義, 如果確要使用此介面, 大體都會內建預設值吧, 如下

  ?

1

2

3

for doc in docs:

for word in doc['words']:

indices. setdefault(word, []) .append(doc['id'])

  這樣就省掉分支了, 代碼看起來少很多.

  不過在某些情況下, setdefault 用起來並不順手: 當 default 值構造很複雜時, 或產生 default 值有副作用時, 以及一個之後會說到的情況; 前兩種情況一言以蔽之, 就是 setdefault 不適用於 default 需要惰性求值的情境. 換言之, 為了兼顧這種需求, setdefault 可能會設計成

  ?

1

2

3

4

def setdefault(self, key, default_factory):

if key not in self:

self[key] = default_factory()

return self[key]

  倘若真如此, 那麼上面的代碼應改成

  ?

1

2

3

for doc in docs:

for word in doc['words']:

indices.setdefault(word, list ).append(doc['id'])

  不過實際上有其它替代方案, 這個最後會提到.

  如果說上面只是一個能預見但實際上可能根本不會遇到的 API 缺陷, 那麼下面這個就略打臉了.

  考慮現在要進行詞頻統計, 即一個詞在文章中出現了多少次, 如果直接拿 dict 來寫, 大致是

  ?

1

2

3

4

5

6

7

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'])

  當你興緻勃勃地跑起上面代碼時, 代碼會以迅雷不及掩臉之勢把異常甩到你鼻尖上 --- 因為出現在 += 操作符左邊的 count.setdefault(word, 0) 在 Python 中不是一個左值. 怎樣, 現在開始念叨 C艸 類型體系的好了吧.

  因為 Python 把預設的字面常量 {} 等價於 dict() 就認為 dict 是銀彈的思想是要不得的; Python 裡面各種資料結構不少, 解決統計問題, 理想的方案是 collections.defaultdict 這個類. 下面的代碼想必看一眼就明白

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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) 的擴充.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.