-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()对象

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循环将逐个遍历每个字符ciphertext,这意味着在字符串中hello world它将遇到该字符l三次,并且每次都对其进行计数。至少,使用字典来跟踪每个字母的计数。

Counter()对象是 Python 字典类型的子类,具有一些额外的行为以使计数更容易。

于 2013-10-04T20:51:08.593 回答