Python中替换密码的问题

2024-10-03 15:33:51 发布

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

很抱歉代码太长,我已经尝试了一段时间来修复主函数中出现的错误。不知道从这里到哪里去

  • 编辑以修复缩进问题,现在函数运行,但命令 “输入命令(getKey、changeKey、encrypt、decrypt、quit):”重复执行,而不考虑getKey以外的输入。当输入getKey时,出现错误“'SubstitutionCipher'对象没有属性'getKey'”
  • 第二次编辑类替换密码允许函数至少为getKey提供一个输出

#A global constant defining the alphabet
LCLETTERS = "abcdefghijklmnopqrstuvwxyz"

#function to check if given key is valid or not

def isLegalKey(key):
    return ( len(key) == 26 and all ( [ch in key for ch in LCLETTERS ] ) )

#function to generate random key
def makeRandomKey():
    lst = list( LCLETTERS )
    random.shuffle( lst )
    return ''.join( lst )
  
  

class SubstitutionCipher:
    def __init__ (self, key = makeRandomKey() ):
        self._key = key
  
    def getKey( self ):
        return self._key
  
    def setKey( self, newKey ):
        self._key = newKey
  
    def encryptText( self, plaintext ):
        alphabet = LCLETTERS
        key = SubstitutionCipher.getKey(self)
        text = plaintext

        result = ""
        for letter in text:
            if letter.lower() in alphabet:
                result += key[alphabet.find(letter.lower())]
            else:
                result += letter

        return result
  
def decryptText( self, ciphertext):
    alphabet = LCLETTERS
    key = SubstitutionCipher.getKey(self)
    text = ciphertext

    result = ""
    for letter in text:
        if letter.lower() in key:
            result += alphabet[key.find(letter.lower())]
        else:
            result += letter

        return result
  
def main():
    flag =0
    cipherFun = SubstitutionCipher()
    while(flag ==0):
        print("Enter a command (getKey, changeKey, encrypt, decrypt, quit): ")
        str = input()
  
        if(str == 'getKey'):
            print(cipherFun.getKey())
  
        elif(str == 'changeKey'):
            temp =0
    while(temp == 0):
        print("Enter a valid cipher key, 'random' for a random key, or 'quit' to quit: ")
        cipher = input()
        if(cipher == 'random'):
            print(makeRandomKey())
            temp = 1
            break;
        elif(cipher == 'quit'):
            temp = 1
            break;
        elif(isLegalKey(cipher) == False):
            print("Illegal key entered. Try again")
    else:
        cipherFun.setKey(cipher)
        print("New cipher key: ", cipherFun.getKey())
        temp = 1
        if(str == 'encrypt'):
            print("Enter a text to encrypt: ")
            str = input()
            res = cipherFun.encryptText(str)
            print("The encrypted text is: ", res)
  
        elif(str == 'decrypt'):
            print("Enter a text to decrypt: ")
            str = input()
            res = cipherFun.decryptText(str)
            print("The decrypted text is: ", res)
  
        elif(str == 'quit'):
            print("Thanks for visiting!")
            flag =1
  
  
        else:
            print("command not recognized. Try again")
  
  
  
  
main()

我不确定这些是语法、缩进、其他特性的问题,还是它们的组合问题。我很感谢你的一些见解,因为我已经尝试了几天来解决这个问题。目前的问题是,中断在循环之外,当更改缩进时,我得到一个错误,称为意外缩进


Tags: keytextinselfifdefresultquit
1条回答
网友
1楼 · 发布于 2024-10-03 15:33:51

这是您的代码,缩进已修复,再加上一些杂项修复。这似乎奏效了

import random
#A global constant defining the alphabet
LCLETTERS = "abcdefghijklmnopqrstuvwxyz"

#function to check if given key is valid or not

def isLegalKey(key):
    return ( len(key) == 26 and all ( [ch in key for ch in LCLETTERS ] ) )

#function to generate random key
def makeRandomKey():
    lst = list( LCLETTERS )
    random.shuffle( lst )
    return ''.join( lst )



class SubstitutionCipher:
    def __init__ (self, key = makeRandomKey() ):
        self._key = key

    def getKey( self ):
        return self._key

    def setKey( self, newKey ):
        self._key = newKey

    def encryptText( self, plaintext ):
        alphabet = LCLETTERS
        key = self._key
        text = plaintext

        result = ""
        for letter in text:
            if letter.lower() in alphabet:
                result += key[alphabet.find(letter.lower())]
            else:
                result += letter

        return result

    def decryptText( self, ciphertext):
        alphabet = LCLETTERS
        key = self._key
        text = ciphertext

        result = ""
        for letter in text:
            if letter.lower() in key:
                result += alphabet[key.find(letter.lower())]
            else:
                result += letter

        return result

#main function
def main():
    flag =0
    cipherFun = SubstitutionCipher()
    while flag ==0:
        print("Enter a command (getKey, changeKey, encrypt, decrypt, quit): ")
        str = input()

        if str == 'getKey':
            print(cipherFun.getKey())

        elif str == 'changeKey':
            while True:
                print("Enter a valid cipher key, 'random' for a random key, or 'quit' to quit: ")
                cipher = input()

                if cipher == 'random':
                    cipherFun.setKey(makeRandomKey())
                    break
                elif cipher == 'quit':
                    break
                elif isLegalKey(cipher) == False:
                    print("Illegal key entered. Try again")
                else:
                    cipherFun.setKey(cipher)
                    print("New cipher key: ", cipherFun.getKey())
                    break
        elif str == 'encrypt':
            print("Enter a text to encrypt: ")
            str = input()
            res = cipherFun.encryptText(str)
            print("The encrypted text is: ", res)

        elif str == 'decrypt':
            print("Enter a text to decrypt: ")
            str = input()
            res = cipherFun.decryptText(str)
            print("The decrypted text is: ", res)

        elif str == 'quit':
            print("Thanks for visiting!")
            flag =1

        else:
            print("command not recognized. Try again")

main()

相关问题 更多 >