使用cesar密码加密文本,str.replace产生TypeError:无法将'NoneType'对象隐式转换为str

时间:2018-09-18 15:28:42

标签: python python-3.x argparse attributeerror caesar-cipher

cipher.py

import argparse

def parse_command_line():  
    parser=argparse.ArgumentParser()
    parser.add_argument("infile",type=str,help="input file to be encrypted or decrypted")

    parser.add_argument("-o outfile_path","--outfile outfile_path",type=str,help="output file")
    parser.add_argument("-k KEY","--key KEY",type=int,default=1,help="encryption/decryption key (must be positive) (default= 1)")
    parser.add_argument("-d","--decrypt",action="store_true",help="decrypt the input file")
    parser.add_argument("-a","--all",action="store_false",help="decrypt using all keys [1, 25], save outputs in different files. (useful in case the key is lost orunknown)")
    parser.add_argument("-v","--verbose",action="store_true",help="Verbose mode")

    args=parser.parse_args()
    return args 
    pass



def transform(message, key, decrypt):

    #TODO: Your code goes here
    if decrypt:
        for i in message:
            temp=shift(i,key)
            transformed_message=message.replace(i,temp,1)
            message=transformed_message
    return transformed_message
    pass
def shift(char, key):     
    # ordered lower case alphabet
    alphabet = "abcdefghijklmnopqrstuvwxyz"

    # will contain shifted lower case alphabet
    shifted_alphabet = ''
    for i in range(len(alphabet)):
        shifted_alphabet = shifted_alphabet + alphabet[(i + key) % 26]

    if char.isalpha():
        char_index = alphabet.index(char.lower())
        shifted_char = shifted_alphabet[char_index]

        # keep char's case (upper or lower)
        if char.isupper():
            return shifted_char.upper()
        else:
            return shifted_char

def main():
    # parse command line arguments
    args = parse_command_line()

    # key is specified
    if not args.all:
        # encrypt/decrypt content of infile
        outstring = transform(instring, args.key, args.decrypt)

        # write content of outstring to outfile
        write_file(outstring, args.outfile)

    # key is not specified, try all keys from 1 to 25 to decrypt infile
    else:
        for k in range(1, 26):
            # decrypt content of infile
            outstring = transform(instring, k, True)

            # write content of outstring to outfile
            write_file(outstring, "decrypted_by_" + str(k) + ".txt")

if __name__ == '__main__':
    main()

我正在使用此命令

$ python3 cipher.py plain_message.txt -k 23 -v -o cipher_message.txt

文件是:

Software is a great combination between artistry and engineering.

--Bill Gates

但这会提供以下回溯:

Traceback (most recent call last):
  File "cipher.py", line 231, in <module>
    main()
  File "cipher.py", line 218, in main
    outstring = transform(instring, k, True)
  File "cipher.py", line 141, in transform
    transformed_message=message.replace(i,temp,1)
TypeError: Can't convert 'NoneType' object to str implicitly

我尝试单独运行transform(message,key, decrypt),它返回的字符串没有问题。

请仅检查parse_command_line()transform(message,key, decrypt), 因为shift()main()是预先编写的,所以它们应该没有问题。

1 个答案:

答案 0 :(得分:1)

您的错误源于您的shift()函数,当遇到文件的第一行文本的最后一个字符时: 'Software is a great combination between artistry and engineering.'

.不是isalpha(),因此shift()函数不会显式返回任何内容,这意味着它将隐式返回None

您的转换方法无法正常处理None

def transform(message, key, decrypt):
    if decrypt:
        for i in message:
            temp=shift(i,key)
            transformed_message=message.replace(i,temp,1) # does not work if temp == None
            message=transformed_message
    return transformed_message
    pass

您可以通过不替换temp is None来避免错误:

def transform(message, key, decrypt): 
    if decrypt:
        for i in message:
            temp=shift(i,key)
            if temp: # check if not Falsy - None is falsy, "if temp is not None:" works too
                transformed_message=message.replace(i,temp,1)

             # assigning something to message does nothing, so removed it
    return transformed_message

如果允许您更改shift()函数本身,我可能只会返回(不变的)非映射字符,该字符也将正常工作。