2017-04-15 94 views
0

我有一本詞典字典,需要計算給定字符串中出現字母對的次數。我得到了字典的工作,我只是完全卡在如何使這個計數器工作...Python字典頻率

無論如何,這是我得到的。任何幫助表示讚賞

test = 'how now, brown cow, ok?' 

def make_letter_pairs(text): 
    di = {} 
    total = len(text)  

    for i in range(len(text)-1): 
     ch = text[i] 
     ach = text[i+1] 
     if ch in ascii_lowercase and ach in ascii_lowercase: 
      if ch not in di: 
       row = di.setdefault(ch, {}) 
       row.setdefault(ach, 0) 

    return di 

make_letter_pairs(test) 
+0

難道你有 看看python中的Counter? https://docs.python.org/2/library/collections.html#collections.Counter –

+0

我沒有。這是做到這一點的唯一方法嗎?或者可以通過添加到我的for循環? – user2951723

+0

字母對出現多少次?該測試字符串的正確輸出是什麼? – davedwards

回答

0

Countercollections模塊是走在這條路上:

代碼:

from collections import Counter 
from string import ascii_lowercase 

def make_letter_pairs(text): 
    return Counter([t for t in [text[i:i+2] for i in range(len(text) - 1)] 
        if t[0] in ascii_lowercase and t[1] in ascii_lowercase]) 

test = 'how now, brown cow, ok?' 
print(make_letter_pairs(test)) 

結果:

Counter({'ow': 4, 'co': 1, 'no': 1, 'wn': 1, 'ho': 1, 'br': 1, 'ok': 1, 'ro': 1})