使用cesar cipher加密文本,str.replace给出TypeError:无法隐式地将'NoneType'对象转换为str

问题描述 投票:0回答:1

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()是预先编写的,这些应该没有问题。

python python-3.x argparse attributeerror caesar-cipher
1个回答
1
投票

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

.不是isalpha()所以shift()函数没有显式返回任何意味着它隐式返回None

你的transform方法不能优雅地处理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()函数本身,我可能只返回(未更改的)非映射字符,它也可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.