for循环一个函数

For loop a function

我正在尝试编写暴力 python 脚本。我正在学习本教程 link 并对其进行了修改以满足我的需要。大多数代码工作正常,除了输出只有一个输出而不是 26

file = args.imp
MAX_KEY_SIZE = 26
message = open(file)

def getKey():
    key = 0
    print("Enter the key number (1-%s)" % (MAX_KEY_SIZE))
    key = int(input())
    while True:
            if (key >= 1 and key <= MAX_KEY_SIZE):
                    return key

def decode(message, key):
    translated = ''


    for symbol in message.read():

            num = ord(symbol)
            num += key

            if num > ord('Z'):
                    num -= 26
            elif num < ord('A'):
                    num += 26
            translated += chr(num)
    return translated


key = getKey()

for k in range(1, MAX_KEY_SIZE + 1):
    print(k, decode(message, key))

输出为:

Enter the key number (1-26)
4
1 BDPWCCONVESDKLOOVACAXKYFJJBGDCSLRRPTYYYIBQNOXLZYHCHCNZCRM
2
3 
4
5
6 etc to 26

你不能像那样一次又一次地读取一个文件。您必须将文件对象的位置设置回开头。否则,message.read() 将只是 return 一个空字符串。添加

message.seek(0)

decode 函数的开头。

调用 read() 后,它会读取整个文件并将读取光标留在文件末尾。当您在这种情况下读取文件时,它将 return 您 '' (空字符串)。这就是原因,您仅在第一次迭代时获得输出,其余为空。

您可以按照@schwobaseggl 的回答查找(将光标指向文件开头)。

或在开头读取所有文件一次,

message = open(file).read()

# code here

def decode(message, key):
    translated = ''
    for symbol in message:
            num = ord(symbol)
            num += key
            if num > ord('Z'):
                    num -= 26
            elif num < ord('A'):
                    num += 26
            translated += chr(num)
    return translated