在python中打印一次副本

2024-06-11 03:50:38 发布

您现在位置: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 %

Tags: 字符串代码inforlendefcount字符
1条回答
网友
1楼 · 发布于 2024-06-11 03:50:38

您只需计算字符数,因此请使用^{} 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 dictionary类型的一个子类,有一些额外的行为使计数更容易。你知道吗

相关问题 更多 >