2013-05-16 38 views
0

我試圖解決這一問題的代碼:計數字典中的每個單詞的數量

def word_counter (input_str): 
    input_str1 = input_str.lower() 
    word = 0 
    input_str2 = dict(enumerate(input_str1.split(), start=1)) 
    if word in input_str2: 
     input_str2[word] += 1 
    else: 
     input_str2[word] = 1 
    return (input_str2) 
word_count_dict = word_counter("This is a sentence") 
print(sorted(word_count_dict.items())) 

,這樣,而不是輸出擺明:

[(0, 1), (1, 'this'), (2, 'is'), (3, 'a'), (4, 'sentence')] 

這反而返回的計數有多少input_str每個字像這樣:

[('a', 1), ('is', 1), ('sentence', 1), ('this', 1)] 

任何幫助,將不勝感激

回答

2

您只能使用collections.Counter

>>> from collections import Counter 
>>> c = Counter('This is a a a sentence'.split()) 
>>> c 
Counter({'a': 3, 'This': 1, 'is': 1, 'sentence': 1}) 
>>> c['a'] 
3 
>>> c['This'] 
1 
>>> c.items() 
[('This', 1), ('a', 3), ('is', 1), ('sentence', 1)] 
相關問題