Python 使用列表理解对列表元素进行Caesar变换
我对Python非常陌生,遇到了一个路障。是否可以使用列表理解对列表中单词的每个字母进行移位?另外,如何以类似的列表理解方式使用ord()和chr() 到目前为止,我有以下代码:Python 使用列表理解对列表元素进行Caesar变换,python,list,list-comprehension,Python,List,List Comprehension,我对Python非常陌生,遇到了一个路障。是否可以使用列表理解对列表中单词的每个字母进行移位?另外,如何以类似的列表理解方式使用ord()和chr() 到目前为止,我有以下代码: def shift( file1="file1.txt", file2 ="file2.txt"): key = int(input("Enter shift key: ")) with open(" file1. txt") as readfile: lines =
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]
我现在只需要执行实际的移位,但我被难住了:/你可以使用
str.join
,在单词列表中的每个ch/字符
上迭代,你可以使用任何你必须创建密码的公式
word_list = ["Foo","Bar","Foobar"]
print(["".join(chr(ord(ch) + 10) for ch in word.lower()) for word in word_list ])
['pyy', 'lk|', 'pyylk|']
下面是一个简单的凯撒变换,使用理解:
>>> string = 'CaesarShift'; shift=3
>>> ''.join(chr(ord('a') + (ord(c)-ord('a')+shift) % 26) for c in string)
'zdhvdupkliw'
这说明了这个概念,但没有试图处理空格或标点符号
可逆性
环绕:凯撒移位是一种环绕移位密码,因此必须有一个环绕字符串的算法
如果你把字母看成数字,那么你可以把字母写成[0, 1…25 ],即<代码>范围(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\u小写
比如:
from string import ascii_lowercase as lowerLetters
def toCaesar(ch):
if ch in lowerLetters:
return chr((chr(ch) - 86)%26 + 96)
else:
return ch
其余的我想您已经有了。此方法提供了一个未解决的错误引用word
from string import ascii_lowercase as lowerLetters
def toCaesar(ch):
if ch in lowerLetters:
return chr((chr(ch) - 86)%26 + 96)
else:
return ch