簡體   English   中英

獲取defaultdict的值

[英]Get the value of a defaultdict

我從一堆或電子郵件中讀取數據並計算每個單詞的頻率。 首先構建兩個計數器:

counters.form = collections.defaultdict(dict)

得到頻率

for word in re.findall('[a-zA-Z]\w*', data):
    counters.form[word][file_name] += 1

對於每個表單,都有一個計數器,用於存儲此單詞出現的所有電子郵件,以及此電子郵件中表單的頻率。 例如

form = {'a':   {'email1':4, 'email2':3}, 
        'the': {'email1':2, 'email3':4},
        'or':  {'email1':2, 'email3':1}}

如何獲取某個電子郵件中某個表單的頻率? 的頻率aemail2是3。

使用Counter類而不是defaultdict可能是個好主意:

Counter是用於計算可哈希對象的dict子類。 它是一個無序集合,其中元素存儲為字典鍵,其計數存儲為字典值。 計數允許為任何整數值,包括零或負計數。 Counter類與其他語言的bag或multisets類似。

您似乎正在構建IR(信息檢索)社區稱為倒排索引的內容。 在這種情況下,我同意你正在采取的整體方法,但也建議你將計數器類默認dict 一起使用 ...

counters.form = collections.defaultdict(collections.Counter)

counters.form將作為壓縮世界模型的一種索引,其中觀察的缺失不是錯誤(也不是假),只是0。

form數據為例,我們填充倒排索引,如...

#-- Build the example data into the proposed structure...
counters.form['a'].update({'email1':4, 'email2':3})
counters.form['the'].update({'email1':2, 'email3':4})
counters.form['or'].update({'email1':2, 'email3':1}})

現在,為了獲得此數據中表單的頻率,我們取消引用它就像是一個二維數組......

print counters.form['a']['email2']

...應該打印3並且與您當前使用的結構大致相同。 這兩種方法的真正區別在於你沒有觀察到。 例如...

print counters.form['noword']['some-email']

使用當前的結構(... collections.defaultdict(dict) ),“noword”對的get counters.form將“小姐”與defaultdict會自動關聯一個新建成的,空的字典counters.form['noword'] ; 然而,當這個空的dict然后被查詢鍵:'some-email'時,空的dict沒有這樣的鍵,導致'some-email'的KeyError異常

如果我們使用建議的結構( collections.defaultdict(collections.Counter) ),那么在counters.form上的'noword'的獲取將會遺漏,並且新的collections.Counter將與鍵'noword'相關聯。 然后當計數器(在第二次取消引用中)查詢“some-email”時,計數器將響應0 - 這是(我相信)所需的行為。

其他一些食譜......

#-- Show distinct emails which contain 'someword'
emails = list(counters.form['someword'])

#-- Show tally of all observations of 'someword'
tally = sum(counters.form['someword'].values( ))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM