在python中打印一次复制

时间:2013-10-04 20:47:25

标签: python

密文是我用来打印重复字符及其出现百分比的字符串。这是代码:

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 %

1 个答案:

答案 0 :(得分: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循环逐个迭代ciphertext中的每个字符,这意味着在字符串hello world中,它会遇到字符l三次,每次算上它。至少,使用字典来跟踪每个字母的计数。

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