我对Python非常陌生,遇到了障碍。是否可以使用列表理解对列表中单词的每个字母进行转换?另外,如何以类似的列表理解方式利用ord()和chr()?
到目前为止,我有以下代码:
def shift( file1="file1.txt", file2 ="file2.txt"):
key = int(input("Enter shift key: "))
with open(" file1. txt") as readfile:
lines = readfile.readlines()
lines = [words.lower() for words in lines]
lines = [ words.split(" ") for words in lines]
我现在所要做的就是执行实际的班次,但是我很沮丧:/
这里是使用理解的简单凯撒平移:
>>> string = 'CaesarShift'; shift=3
>>> ''.join(chr(ord('a') + (ord(c)-ord('a')+shift) % 26) for c in string)
'zdhvdupkliw'
这说明了这个概念,但没有尝试处理空格或标点符号。
>>> new = ''.join(chr(ord('a') + (ord(c)-ord('a')+shift) % 26) for c in string.lower())
>>> ''.join(chr(ord('a') + (ord(c)-ord('a')-shift) % 26) for c in new)
'caesarshift'
您可以使用str.join
,从ch/character
遍历每个word
中的每个word_list
,您可以使用创建密码的任何公式。
word_list = ["Foo","Bar","Foobar"]
print(["".join(chr(ord(ch) + 10) for ch in word.lower()) for word in word_list ])
['pyy', 'lk|', 'pyylk|']
Wrap Around:Caesar Shift是一种环绕移位密码,因此您必须有一种环绕字符串的算法。
如果将字母视为数字,则可以将字母写为[0,1 ... 25],即range(26)
。
如果对此进行10的凯撒平移,您将得到:[10,11 ... 25,26 ... 35]。
字符26不在字母表中。您需要将其更改为0。然后将字符27更改为1,依此类推。因此,您要查找的转换(如果字母从0到25排列)为mod( letterValue + 10, 26)
。
但是,字母不是从0开始,因此您必须先减去ord('a')
的值,然后再添加。
上式中的letterValue
简单来说是:ord(ch) - ord('a')
。因此,将较早的表达式更改为(chr(ch) - ord('a') + 10) % 26
。
然后使用chr((chr(ch) - ord('a') + 10) % 26 + ord('a'))
将其更改回去。
由于ord('a')
为96
,因此您可以使用chr((chr(ch) - 96 + 10)%26 + 96)
,即chr((chr(ch)-86)%26 + 96)
]]稍微加快此过程。
非字母字符:?
和!
等字符将转换为什么?这些通常保持不变。您可以为其提供if
条件,并检查所请求的字符是否在string.ascii_lowercase
中。
类似:
from string import ascii_lowercase as lowerLetters
def toCaesar(ch):
if ch in lowerLetters:
return chr((chr(ch) - 86)%26 + 96)
else:
return ch
其余的我想你已经有了。