【发布时间】:2017-08-15 02:13:33
【问题描述】:
我已经研究这段代码好几天了,但没有结果。函数autodecrypt 接受由encrypt 加密的字符串,其域A-Z 和a-z 中的字符由数字offset 更改。因此,在 ASCII 代码中,“A”为 65,如果 offset = 7,则“A”现在为“H”(其代码 # 为 72)。将尝试 0-95 的偏移值。如果 85% 或更多的单词出现在名为dictionary.txt 的 txt 文件中,则将检查解密,该文件基本上包含一堆常用单词。这就是我的问题所在:它没有正确检查我生成的字符串是否在 txt 文件中。
def autodecrypt(ciphertext):
text = list(ciphertext)
t = open ('dictionary.txt', 'r')
m = t.read()
diccond = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ' #initializing variables
ntext = []
ctext = ''
i = 0
offset = 0
check = 0
while offset <= 95: #cycling through 95 offset values
while i < len(text): #decrypting ciphertext with given offset value
r = ord(text[i])
if r - offset < 32:
s = chr(127 - (offset - (r - 32)))
else:
s = chr(r - offset)
ntext.append(s)
i+=1
stext = ''.join(ntext) #make decrypted list (ntext) into string, stext
for j in stext: #removing punctuation and store in new string, ctext
if j in diccond:
ctext += j
cltext = ctext.lower() #lowercasing ctext string
for k in (cltext.split(' ')): #checking if ctext, list version, is in txt file
if k in m:
check +=1
if check / len(ctext.split(' ')) >= 0.85: #checking if 85% or over of ctext string version in txt file
return stext
else: #else if there is not any fail and return cipher text (see below)
fail = 0
check = 0 #resetting all variables
ctext = ''
ntext=[]
i=0
offset +=1 #increasing offset
if fail == 0:
return ciphertext
此外,如果没有 85% 或更多匹配,则返回原始加密字符串。
【问题讨论】:
-
当前的问题是您在循环中(在另一个循环中)使用
m = t.read(),但是在第一次迭代之后,t.read()将返回一个空字符串。您应该在开头阅读文件并使用结果。这是最干净的方法。此外,您可能应该将字典中的单词放在set中,这样不会很慢。 -
是的,我在发布后对其进行了编辑,但它仍然无法正常工作。专门针对这个测试用例,原文是
'Je pense, donc, je suis.',密文是'Wr-}r{!r9-q|{p9-wr-!#v!;'。原始文本中的单词不在 txt 文件中,因此它应该返回加密文本,尽管它返回'f"<-"+0"H<!,+ H<\'"<02&0J' -
使用密文运行代码时 = 'Wr-}r{!r9-q|{p9-wr-!#v!;'一个空的 dictionary.txt 它返回正确的结果为 'Wr-}r{!r9-q|{p9-wr-!#v!;'。一些更具体的测试数据会有所帮助。当您尝试在字典文件中查找 'je' 并且它包含一个类似 'meje' 的单词时会很受欢迎。
-
“检查不正确”是什么意思?你观察到什么行为?有例外还是只是输出不好?什么是糟糕的输出,它与您的预期有何不同?
标签: python dictionary encryption