加密文件中的行

时间:2013-03-07 00:34:46

标签: python

我正在尝试编写一个打开文本文件的程序,并将文件中的每个字符向右移动5个字符。它应该只对字母数字字符执行此操作,并保留非字母数字。 (例如:C变为H)我应该使用ASCII表来执行此操作,并且当字符环绕时我遇到了问题。例如:w应该成为b,但是我的程序给了我一个ASCII表中的字符。我遇到的另一个问题是所有的字符都在不同的行上打印,我希望它们都能在同一行上打印。 我不能使用列表或词典。

这就是我所拥有的,我不知道如何做最后的if语句

def main():
    fileName= input('Please enter the file name: ')
    encryptFile(fileName)


def encryptFile(fileName):
    f= open(fileName, 'r')
    line=1
    while line:
       line=f.readline()
       for char in line:
           if char.isalnum():
               a=ord(char)
               b= a + 5
               #if number wraps around, how to correct it
               if 

                print(chr(c))
            else:
                print(chr(b))
        else:
            print(char)

3 个答案:

答案 0 :(得分:7)

使用str.translate

In [24]: import string

In [25]: string.uppercase
Out[25]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [26]: string.uppercase[5:]+string.uppercase[:5]
Out[26]: 'FGHIJKLMNOPQRSTUVWXYZABCDE'

In [27]: table = string.maketrans(string.uppercase, string.uppercase[5:]+string.uppercase[:5])

In [28]: 'CAR'.translate(table)
Out[28]: 'HFW'

In [29]: 'HELLO'.translate(table)
Out[29]: 'MJQQT'

答案 1 :(得分:1)

首先,重要的是它是大写还是大写。我将在这里假设所有字符都是小写字母(如果它们不是,则很容易制作它们)

if b>122:
    b=122-b  #z=122
    c=b+96   #a=97

在ASCII中w = 119并且z = 122(ASCII中的十进制)所以119 + 5 = 124和124-122 = 2这是我们的新b,然后我们将其添加到a-1(如果我们这需要照顾得到1回,2 + 96 = 98和98是b。

对于在同一行上打印,而不是在拥有它们时打印,我会将它们写入列表,然后从该列表中创建一个字符串。

而不是

    print(chr(c))
else:
    print(chr(b))

我愿意

     someList.append(chr(c))
else: 
     somList.append(chr(b))

然后将列表中的每个元素连接成一个字符串。

答案 2 :(得分:0)

您可以创建一个dictionary来处理它:

import string
s = string.lowercase + string.uppercase + string.digits + string.lowercase[:5]
encryptionKey = {s[i]:s[i+5] for i in range(len(s)-5)}

s+ string.lowercase[:5])的最后加数将前5个字母添加到密钥中。然后,我们使用简单的字典理解来创建加密密钥。

加入你的代码(我也改了它,所以你遍历这些行而不是使用f.readline()

import string
def main():
    fileName= input('Please enter the file name: ')
    encryptFile(fileName)


def encryptFile(fileName):
    s = string.lowercase + string.uppercase + string.digits + string.lowercase[:5]
    encryptionKey = {s[i]:s[i+5] for i in range(len(s)-5)}
    f= open(fileName, 'r')
    line=1
    for line in f:
       for char in line:
           if char.isalnum():
               print(encryptionKey[char])
           else:
                print(char)
相关问题