首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Vigenere元组错误

Python Vigenere元组错误
EN

Stack Overflow用户
提问于 2017-03-17 12:49:32
回答 2查看 279关注 0票数 1

我在试着做一个Vigenere密码。当我试图加密消息时,我会得到以下错误。

代码语言:javascript
复制
    cipherCharIndexValue = baseAlphabet.index(keyList[keyIncrement]) + baseAlphabet.index(plainTextChar)
ValueError: tuple.index(x): x not in tuple

我不知道是什么问题导致了错误,有什么帮助吗?

代码语言:javascript
复制
baseAlphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')

plainText = input("Please enter the plain text")
key = input("Please enter the key word")
keyList = []
keyLength = 0
while keyLength < len(plainText):
    #Adds the users entered key into a list character by character. 
    #Also makes the key the same length as plainText
    for char in key:
        if keyLength < len(plainText):
            keyList.append(str(char))
            keyLength = keyLength + 1

#The variable each processed letter is appended to
completeCipherText = [] 
#This is the value used to temporaily store the ciphertext character during the iteration
cipherCharIndexValue = 0
keyIncrement = 0

#iterates through the plain text
for plainTextChar in plainText:
        #Adds the base alphabets index value of the key and the plain text char
        cipherCharIndexValue = baseAlphabet.index(keyList[keyIncrement]) + baseAlphabet.index(plainTextChar)
        while cipherCharIndexValue > 25:
             #makes the addition value under 26 as to not go out of range of base alphabet tuple
            cipherCharIndexValue = cipherCharIndexValue - 26 
         #appends the ciphertext character to the completeCipherText variable. 
         #The character is the index of the key + index of the       plainTextChar from baseAlphabet
        completeCipherText.append(baseAlphabet[cipherCharIndexValue])
         #Moves onto the next key
        keyIncrement = keyIncrement + 1
print ('').join(completeCipherText)#Makes the result a strings for printing to the console.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-17 13:51:51

每当尝试获取不在ValueError: tuple.index(x): x not in tuple中的char索引时,就会得到这个baseAlphabet错误。因此,您需要确保key只包含这样的字符,并且在编码plainText时,要么避免对“坏”字符进行编码,然后将它们复制到completeCipherText列表,要么将它们转换为有效的baseAlphabet字符。

在传统加密中,通常将所有空格和标点符号转换为另一个字符(如'x''.' )。我决定将'.'添加到baseAlphabet中,并编写一个小函数fix_string来执行该操作。fix_string还确保所有字母都是小写的。

我还对您的代码做了其他一些小的简化。

baseAlphabet不需要是元组。我们可以用绳子。但是,如果您确实想使用单个字符的元组,则不需要完整地写出它,只需将一个字符串传递给tuple构造函数,例如

代码语言:javascript
复制
tuple("some string")

我们通常不需要跟踪列表、字符串等集合的长度。所有内置的集合都跟踪自己的长度,我们可以使用len()函数有效地访问该长度。

我们不需要keyIncrement。相反,我们可以使用keyList函数并行地遍历plainTextzip的字符。

而不是使用一个循环来确保键和plainText指数的和在适当的范围内,我们可以使用%模算子。

代码语言:javascript
复制
from __future__ import print_function

baseAlphabet = 'abcdefghijklmnopqrstuvwxyz.'

# Process s so that it only contains chars in baseAlphabet
def fix_string(s):
    # Convert to lower case
    s = s.lower()
    # Convert "other" chars to dot
    a = [ch if ch in baseAlphabet else '.' for ch in s]
    return ''.join(a)

# Vignere cipher
# mode = 1 to encode, -1 to decode
def vignere(plainText, key, mode):
    keyList = []
    while len(keyList) < len(plainText):
        # Adds the key into a list character by character. 
        # Also makes the key the same length as plainText
        for char in key:
            if len(keyList) < len(plainText):
                keyList.append(str(char))

    # The variable each processed letter is appended to
    completeCipherText = []

    # iterates through the plain text
    for keyChar, plainTextChar in zip(keyList, plainText):
        # Adds the base alphabet's index value of the plain text char and the key char
        cipherCharIndexValue = baseAlphabet.index(plainTextChar) 
        cipherCharIndexValue += mode * baseAlphabet.index(keyChar)
        # makes the addition value in range(len(baseAlphabet))
        cipherCharIndexValue = cipherCharIndexValue % len(baseAlphabet)

        # appends the ciphertext character to the completeCipherText variable. 
        # The character is the index of the key + index of the plainTextChar from baseAlphabet
        completeCipherText.append(baseAlphabet[cipherCharIndexValue])

    # Makes the result a string
    return ''.join(completeCipherText)

# Test

# plainText = raw_input("Please enter the plain text")
# key = raw_input("Please enter the key word")

plainText = 'This, is a test string!'
key = 'the key'

# Process plainText and key so that they only contain chars in baseAlphabet
plainText = fix_string(plainText)
key = fix_string(key)

ciphertext = vignere(plainText, key, 1)
print(ciphertext)

decoded = vignere(ciphertext, key, -1)
print(decoded)

输出

代码语言:javascript
复制
lomrjdfkgezciplgwsamkzg
this..is.a.test.string.
票数 0
EN

Stack Overflow用户

发布于 2017-03-17 12:56:50

似乎您正在使用python2.x,您应该使用raw_input而不是input

如果输入字符串中有空格或其他标点符号,您的代码就会崩溃,所以我建议您在使用keyList[keyIncrement]方法之前确保indexindex中,如果它不在这个元组中,您将得到以下错误:

代码语言:javascript
复制
ValueError: tuple.index(x): x not in tuple

例如:

代码语言:javascript
复制
if keyList[keyIncrement] in keyList:
    cipherCharIndexValue = baseAlphabet.index(keyList[keyIncrement]) + baseAlphabet.index(plainTextChar)

也可以使用try/catch捕获异常,以便调试代码。

希望这能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42858038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档