-1

暗号文は、重複した文字とその出現率を出力するために使用した文字列です。コードは次のとおりです。

def freq_attack (ciphertext):
    store = ""
    character = ""
    non_character=""
    for i in xrange(len(ciphertext)):
        x = ciphertext[i]
        if(is_alphabet(x)):
            character +=x
        else:
            non_character +=x
    for char in character:
        count =(ciphertext.count(char)*100)/len(character)
        print char, count,"%"

出力は

a 400/7 %
s 100/7 %
a 400/7 %
a 400/7 %
e 100/7 %
a 400/7 %
w 100/7 %
4

1 に答える 1

4

文字を数えるだけでよいので、collections.Counter()objectを使用します。

from collections import Counter

def freq_attack(ciphertext):
    counts = Counter(ch for ch in ciphertext if ch.isalpha())
    total = sum(counts.itervalues())

    for char, count in counts.most_common():
        print char, count * 100.0 / total

デモ:

>>> freq_attack('hello world')
l 30.0
o 20.0
e 10.0
d 10.0
h 10.0
r 10.0
w 10.0

ループforは各文字を 1 つずつ繰り返します。ciphertextつまり、文字列内でその文字に 3 回hello world遭遇し、lそのたびにカウントします。少なくとも、辞書を使用して各文字のカウントを追跡します。

このCounter()オブジェクトは Python 辞書型のサブクラスであり、カウントを容易にするための追加の動作がいくつかあります。

于 2013-10-04T20:51:08.593 に答える