频率分析问题与元组错误

时间:2015-04-23 13:31:28

标签: python encryption tuples frequency frequency-analysis

在match_letters函数中,使用' place = string.index(letter)'我一直收到同样的错误:值错误:tuple.index(x):x不是元组。'有谁知道如何解决这个问题?非常感谢:)谢谢

def freq_analysis():
""" Summary:    Perform a frequency analysis on a string
    Paramaters: text - The text to analyse
    Returns:    A string containing the deciphered text
"""
    text = input("enter text")
    letterCount = getLetterCount(text)


    Letter_Count_Tuple,new_letter_count,descending = descending_order(letterCount)
    ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
    string = descending_order(letterCount)
    finish = match_letters(ETAOIN, string,text)

def getLetterCount(text):
    letterCount = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0}
    for letter in text.upper():
        if letter in letterCount:
            letterCount[letter] += 1

    print("Letter count is",letterCount)
    return letterCount

def descending_order(letterCount):
    Letter_Count_Tuple = letterCount.items()
    new_letter_Count = sorted(Letter_Count_Tuple, key = get_number)
    print("new letter count is",new_letter_Count)
    descending = new_letter_Count[::-1]
    print("descending is",descending)
    string = ""
    for le in descending:
        string = string + le[0]

    print("String is",string)
    return Letter_Count_Tuple, new_letter_Count, string

def get_number(Letter_Count_Tuple):
    return Letter_Count_Tuple[1]

def match_letters(ETAOIN,string,text):

# loop over each leter in the encrypted text
    # find the position of that letter in your observed descending order string
    # replace it with the letter in the same position from the etaoin descending order string
    finish = ""
    for letter in text:
     place = string.index(letter)
     ETAOIN_place = ETAOIN[place]
     for le in ETAOIN_place:
        finish = finish + le
     print(finish)

freq_analysis()

Traceback:
Message File Name       Line    Position       
Traceback                              
    <module>    <module1>       54             
    freq_analysis       <module1>       13             
    match_letters       <module1>       47             
ValueError: tuple.index(x): x not in tuple

1 个答案:

答案 0 :(得分:0)

您在此处传递给 match_letters 的变量字符串

string = descending_order(letterCount)
finish = match_letters(ETAOIN, string,text)

不是字符串(或列表),它是来自 descending_order 的元组:

return Letter_Count_Tuple, new_letter_Count, string

要么只返回 descending_order 中的字符串,要么从返回的元组中正确地选择它:

_,_,string = descending_order(letterCount)

(我假设 descending_order 中的字符串 match_letters 中所需的字符串