2013-11-24 94 views
0

我想組裝一個函數,該函數允許我從給定字符串甚至文本文件創建字典。從字符串/文本文件創建字典

例如:

statement = "tell me what you want what you really really want" 

我想最終的結果看起來是這樣:

{tell: 1, me:1, what: 2, you: 2, want: 2, really: 2} 

字符串中的字符鍵,而它出現的次數是價值。

+1

導入'Counter',只是做'計數器(statement.split ())' – Blender

回答

2

使用collections.Counter(),傳遞文字序列數:

>>> from collections import Counter 
>>> Counter('tell me what you want what you really really want'.split()) 
Counter({'you': 2, 'really': 2, 'what': 2, 'want': 2, 'tell': 1, 'me': 1}) 
1

沒有進口任何物件:從`collections`

statement = "tell me what you want what you really really want" 

end_result = dict() 

for word in statement.split(): 
    end_result[word] = end_result.get(word, 0) + 1