2017-04-15 121 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})