对文件中的行进行加密
我正在尝试写一个程序,这个程序可以打开一个文本文件,然后把文件里的每个字符向右移动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
你可以创建一个字典来处理这个问题:
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)
1
首先,字母的大小写是很重要的。我这里假设所有的字母都是小写的(如果不是,也很容易把它们转换成小写)。
if b>122:
b=122-b #z=122
c=b+96 #a=97
w在ASCII码中是119,z是122(这是它们的十进制值),所以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))
然后把列表中的每个元素连接成一个字符串。
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'