我的Caeser密码在shell中与字符串交互工作,但是当我尝试执行单独的程序来加密和解密时,我遇到了一些问题,我不知道输入是否被拆分成一个列表,但加密函数中的if语句被绕过,并默认为填充的else语句名单未加密。有什么建议,谢谢。我在用文件实用程序.py从戈德瓦瑟的书中。那个文件在第11章的http://prenhall.com/goldwasser/sourcecode.zip,但我不认为问题出在这个地方,但谁知道呢。提前谢谢。在
#CaeserCipher.py
class CaeserCipher:
def __init__ (self, unencrypted="", encrypted=""):
self._plain = unencrypted
self._cipher = encrypted
self._encoded = ""
def encrypt (self, plaintext):
self._plain = plaintext
plain_list = list(self._plain)
i = 0
final = []
while (i <= len(plain_list)-1):
if plain_list[i] in plainset:
final.append(plainset[plain_list[i]])
else:
final.append(plain_list[i])
i+=1
self._encoded = ''.join(final)
return self._encoded
def decrypt (self, ciphertext):
self._cipher = ciphertext
cipher_list = list(self._cipher)
i = 0
final = []
while (i <= len(cipher_list)-1):
if cipher_list[i] in cipherset:
final.append(cipherset[cipher_list[i]])
else:
final.append(cipher_list[i])
i+=1
self._encoded = ''.join(final)
return self._encoded
def writeEncrypted(self, outfile):
encoded_file = self._encoded
outfile.write('%s' %(encoded_file))
#encrypt.py
from FileUtilities import openFileReadRobust, openFileWriteRobust
from CaeserCipher import CaeserCipher
caeser = CaeserCipher()
source = openFileReadRobust()
destination = openFileWriteRobust('encrypted.txt')
caeser.encrypt(source)
caeser.writeEncrypted(destination)
source.close()
destination.close()
print 'Encryption completed.'
进入
^{pr2}$source
是一个file对象-这个代码“工作”(不加密任何东西)这一事实很有趣-结果是在迭代之前,您在源代码上调用list()
,这将它转换为文件中的一个行列表。而不是通常的list(string)
的结果,这是一个字符列表。因此,当它试图加密每个chracter时,它会发现一整行与您设置的任何替换项都不匹配。在同样,正如其他人指出的那样,您忘记在代码中包含plainset,但这并不重要。在
一些关于你的代码的随机注释(可能是吹毛求疵,呵呵)
for item in string:
-字符串已经作为字节列表工作,就像您试图转换的那样。在outfile.write(self._encoded)
编辑:如果有人想知道这些文件函数做什么以及它们为什么工作,他们会在while循环中调用
raw_input()
,直到有合适的文件可以返回。openFileWriteRobust()
有一个参数,该参数是用户不输入任何内容时的默认值。代码链接在操作站上。在一些要点:
with
)可确保文件在读或写后关闭。在encrypt
和{writeEncrypted
方法只是文件write方法的包装器。因此该类实际上只有两个方法,其中一个是__init__
。在记住这一点,你的代码可以用这个来代替
如果使用13的移位,则可以使用内置的
rot13
编码器。在对我来说,在调用
openFileReadRobust()
之后,source
中不会有任何内容。我不知道openFileReadRobust()
的规范,但它似乎不知道要打开什么文件,除非有一个文件名作为参数给定,而且没有文件名。在因此,我怀疑}也是空的。在
source
是空的,因此{我建议打印出},以确保它们的值是您期望的值。在
source
、plaintext
和{顺便说一句,
openFileReadRobust()
函数对于我来说似乎没有什么帮助,如果它可以为非感官参数值返回非感官值。我非常希望我的函数在这种情况下立即抛出异常。在相关问题 更多 >
编程相关推荐