问题
In the match_letters function, with 'place = string.index(letter)' i keep recieving the same error of 'Value Error: tuple.index(x): x not a tuple.' Does anyone know how to solve this? It will be much appreciated :) Thanks
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:
The variable string you're passing to match_letters here:
string = descending_order(letterCount)
finish = match_letters(ETAOIN, string,text)
is not really a string (or list), it's a tuple from descending_order:
return Letter_Count_Tuple, new_letter_Count, string
Either return just the string in descending_order or pick it up properly from the returned tuple:
_,_,string = descending_order(letterCount)
(I'm assuming that the string inside descending_order is the one you want in match_letters)
来源:https://stackoverflow.com/questions/29825013/frequency-analysis-issues-with-tuple-error