替换字符串中的所有字母

2024-04-19 23:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用单字母替换加密的字符串,我想用英语的频率分析来破解它(不是为了解决它,而是为了丰富我的编程技巧)。你知道吗

我目前处于这样一种情况,即在tuple的排序列表中表示的字符串中,字母出现的频率如下:[('V', freqV), ('D', freqD)...](注意,在本例中,V是比任何其他字母出现得更多的字母,因此freqV是列表中tuple中出现的最大数字),以及英语用同样的方式表达。你知道吗

在这种情况下,如何正确替换字母?你知道吗

我已经尝试过简单的正面解决方案:

new_text = str(cipher_str)

for i in xrange(26): #26 is the length of both lists, obviously
    new_text = new_text.replace(sorted_cipher_freq[i][0], sorted_eng_freq[i][0])

但它不起作用(原因之一是有时替换的字符与解密的字符相同)。例如ap=an,因此字母a在解密和加密时是相同的,但p应该是n)。你知道吗

我该怎么办?你知道吗


Tags: 字符串text列表new编程字母情况字符
2条回答

你可以用最高的频率把它和最高的N频率匹配起来。。。像这样的

en_freq="ETAOINSHDLUCMFYWGPBVKXQJZ" #from http://www.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html
encoded_text =open("encrypted.txt").read().upper()#normalize to uppercase
sorted_my_frequency = Counter(encoded_text).most_frequent(len(en_freq)) #we want the 25 most frequent characters (sorted
my_frequency=join(sorted_my_frequency)[:len(en_freq)]

translation_table = string.maketrans(my_frequency,en_freq) #map our most frequent  to expected english frequencies

print encoded_text.translate(translation_table) #apply the translation_table
#note that you need a fairly large ammount of text for this to work very well ... and you will likely still need to manually translate some parts

请注意,可能有一些小错误,因为我实际上没有运行这个或有任何目标文本进行解码

可能的做法是一个字符接一个字符:

sorted_cipher_freq = [('V', 25), ('D', 10)]
simple_cipher_freq = [letter for letter, freq in sorted_cipher_freq]

en_freq="ETAOINSHDLUCMFYWGPBVKXQJZ"

new_text = ''
for char in cipher_str:
    new_char = en_freq[simple_cipher_freq.index(char)]
    new_text += new_char

print new_text

相关问题 更多 >