【发布时间】:2013-03-29 22:23:22
【问题描述】:
最终我将能够在聊天室中发布类似这样的简单问题,但现在我必须发布它。我仍在努力解决 Python 中的比较问题。我有一个包含从文件中获得的字符串的列表。我有一个函数,它接收单词列表(以前从文件创建)和一些“密文”。我正在尝试使用 Shift Cipher 蛮力破解密文。我的问题与比较整数相同。虽然我在尝试使用打印语句进行调试时可以看到,我的密文将被转移到单词列表中的一个单词,但它永远不会评估为 True。我可能正在比较两种不同的变量类型,或者 /n 可能会导致比较失败。对不起今天的所有帖子,我今天正在做很多练习题,为即将到来的作业做准备。
def shift_encrypt(s, m):
shiftAmt = s % 26
msgAsNumList = string2nlist(m)
shiftedNumList = add_val_mod26(msgAsNumList, shiftAmt)
print 'Here is the shifted number list: ', shiftedNumList
# Take the shifted number list and convert it back to a string
numListtoMsg = nlist2string(shiftedNumList)
msgString = ''.join(numListtoMsg)
return msgString
def add_val_mod26(nlist, value):
newValue = value % 26
print 'Value to Add after mod 26: ', newValue
listLen = len(nlist)
index = 0
while index < listLen:
nlist[index] = (nlist[index] + newValue) % 26
index = index + 1
return nlist
def string2nlist(m):
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
newList = []
msgLen = len(m) # var msgLen will be an integer of the length
index = 0 # iterate through message length in while loop
while index < msgLen:
letter = m[index] # iterate through message m
i = 0
while i < 26:
if letter == characters[i]:
newList.append(numbers[i])
i = i + 1
index = index + 1
return newList
def nlist2string(nlist):
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
newList = []
nListLen = len(nlist)
index = 0
while index < nListLen:
num = nlist[index]
newNum = num % 26
i = 0
while i < 26:
num1 = newNum
num2 = numbers[i]
if (num1 == num2):
newList.append(characters[i])
i = i + 1
index = index + 1
return newList
def wordList(filename):
fileObject = open(filename, "r+")
wordsList = fileObject.readlines()
return wordsList
def shift_computePlaintext(wlist, c):
index = 0
while index < 26:
newCipher = shift_encrypt(index, c)
print 'The new cipher text is: ', newCipher
wordlistLen = len(wlist)
i = 0
while i < wordlistLen:
print wlist[i]
if newCipher == wlist[i]:
return newCipher
else:
print 'Word not found.'
i = i + 1
index = index + 1
print 'Take Ciphertext and Find Plaintext from Wordlist Function: \n'
list = wordList('test.txt')
print list
plainText = shift_computePlaintext(list, 'vium')
print 'The plaintext was found in the wordlist: ', plainText
当移位量 = 18 时,密文 = 名称,这是我的单词列表中的一个单词,但它永远不会评估为 True。提前感谢您的帮助!
【问题讨论】:
-
尝试打印
repr(x)而不是x。这将使您更容易看到额外的'\n'或其他空白字符,以及区分'2'和2,以及您正在谈论的所有其他内容。 -
同时,您能否给我们
test.txt的内容,并修复缩进,并包含一个完整的示例(所有这些函数shift_encrypt调用),这样我们就可以实际运行您的代码并进行调试是吗? -
附带说明,调用变量
list是个坏主意,因为这是内置list类型的名称,您将无法再访问它。 -
对不起!好的,所以 test.txt 每行包含一个单词: 你好,我的名字是 jesi 这就是它的全部内容,因为我只是在测试它。我将编辑以上内容以添加其他功能。
-
@abarnert 好的,所以我添加了我认为运行/调试所需的所有内容。我将变量名称列表更改为其他名称,感谢您的帮助!
标签: python list string-comparison