2017-04-15 5 views
0

私は辞書の辞書を持っており、与えられた文字列に文字ペアが何回現れるかを数えておく必要があります。私は仕事のための辞書を持って、私はちょうどこれのためのカウンタワークを作る方法に完全に固執しています...Python辞書の頻度

とにかく、私は何を持っています。すべてのヘルプはcollectionsモジュールから

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

Counterを高く評価され、この上に行くための方法です:

コード:

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})