尝试不使用';作战需求文件';用Python

尝试不使用';作战需求文件';用Python,python,Python,因此,我正在尝试编写代码,将文本文件转换为数字,然后在其中添加偏移因子,以便在稍后转换为ASCII时更改字母-所有操作都非常有效,直到我不必使用“ord(x)”将空格转换为数字为止 代码如下: def TextFileEncyption(OFkey, Str): '''This will convert the text file that the user inputted earlier, using the offset factor to do so''' Message

因此,我正在尝试编写代码,将文本文件转换为数字,然后在其中添加偏移因子,以便在稍后转换为ASCII时更改字母-所有操作都非常有效,直到我不必使用“ord(x)”将空格转换为数字为止

代码如下:

def TextFileEncyption(OFkey, Str):
    '''This will convert the text file that the user inputted earlier, using the offset factor to do so'''
    Message = ""
    print("The program is now going to encrypt your chosen text file...")
    for x in Str:
        if x == 32:
            pass
        else:
            number = ord(x)
        newNumber = number+OFkey
        if newNumber > 126:
            newNumber = newNumber - 94
        ASCIIletter = chr(newNumber)
        Message += ASCIIletter
    print(Message)
我试过的代码是
'If x==space'
(其中space是一个变量,如
space=”“
),代码是
'If x==“”

我怎样才能最好地解决这个问题?谢谢

您必须使用:

if x == ' ':

但无论如何,算法中存在一个问题。如果
Str
参数以空格开头怎么办?您的
编号
变量在第一次传递时未定义。

正如dlask所说,如果x='',您可以使用。你已经试过了。我相信你遇到的问题实际上并不在这方面。当您有一个空格时,可以跳过第一个if/else语句

    newNumber = number+OFkey
    if newNumber > 126:
        newNumber = newNumber - 94
    ASCIIletter = chr(newNumber)
    Message += ASCIIletter
但是,“number”仍然是从上一个字母设置的,这最终会导致在空格之前重复该字符。当输入为空格时,下面的代码将加密的字母设置为空格。这就是你想要的吗

for x in Str:
    if x == ' ':
        ASCIIletter = ' '
        pass
    else:
        number = ord(x)
        newNumber = number+OFkey
        if newNumber > 126:
            newNumber = newNumber - 94
        ASCIIletter = chr(newNumber)
    Message += ASCIIletter
print(Message)

问题是您希望保留空格,但通过旋转偏移量来加密所有其他字符

比如:

def TextFileEncyption(offset, txt):
    '''This will convert the text file that the user inputted earlier, 
       using the offset factor to do so'''
    Message = ""
    print("The program is now going to encrypt your chosen text file...")
    # go through each character in the input text
    for char in txt:
        number = ord(char)
        # ...and only modify characters that are *not* a space character
        if number != 32:
            number = number + offset
            if number > 126:
                number -= 94
        # ...then convert the value back into a character
        ASCIIletter = chr(number)
        # and append it to the message variable for output.
        Message += ASCIIletter
    print(Message)



if __name__ == "__main__":
    import sys
    inText = "This is a test of the function."
    if len(sys.argv) > 1:
        inText = sys.argv[1]
    TextFileEncyption(10, inText)
给出如下输出:

bgporter@Ornette ~/temp:python soEncrypt.py "A test of the encryption function."
The program is now going to encrypt your chosen text file...
K ~o}~ yp ~ro oxm|%z~syx p!xm~syx8

您能否给出预期输入和输出的示例,以及代码的输出与预期的不同之处?如果x='',则
没有问题。到底是什么问题?它以什么方式不起作用?@bgporter好的,每次代码运行时都会生成一个8个字符的密钥,因此每次对代码进行不同的加密-但是,我希望文件中应用了“ord(x)”的部分之间有空格,但是空间被转换了。我回到学校后会测试这个,但理解正是我需要的!谢谢很高兴这有帮助。