使用单词列表的 Python 字符串比较

标签 python list string-comparison

最终我将能够在聊天室中发布像这样的简单问题,但现在我必须发布它。我仍在努力解决 Python 中的比较问题。我有一个包含从文件中获取的字符串的列表。我有一个接受单词列表(以前从文件创建)和一些“密文”的函数。我正在尝试使用 Shift Cipher 蛮力破解密文。我的问题与比较整数相同。尽管我在尝试使用 print 语句进行调试时可以看到,我的密文将被转移到单词列表中的一个单词,但它永远不会计算为 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。提前感谢您的帮助!!

最佳答案

目前我们掌握的信息很难确定,但这里有一个猜测:

wordsList = fileObject.readlines()

这将返回一个保留换行符的列表字符串,例如:

['hello\n', 'my\n', 'name\n', 'is\n', 'jesi\n']

因此,在 shift_computePlaintext 中,当您遍历 wlist 寻找与解密的 'vium' 匹配的内容时,您正在寻找匹配 'name' 的字符串,但都不匹配,包括 'name\n'

换句话说,正是您所怀疑的。

有几种方法可以解决这个问题,但最明显的是使用 wlist[i].strip() 而不是 wlist[i],或者首先通过使用类似 wordsList = [line.strip() for line in fileObject] 而不是 wordsList = fileObject.readlines() 来剥离所有内容。


一些旁注:

调用 readlines() 几乎从来没有充分的理由。这会返回一个您可以迭代的行列表……但是文件对象本身已经是一个可迭代的行,您可以对其进行迭代。如果您真的需要确保它是一个列表而不是某种其他类型的可迭代对象,或者制作一个单独的副本以备后用,或者其他什么,只需对其调用 list ,就像您对任何其他可迭代对象所做的那样。

你几乎不应该像这样写一个循环:

index = 0
while index < 26:
    # ...
    index = index + 1

相反,只需这样做:

for index in range(26):

它更容易阅读,更难出错(微妙的差一错误是造成你一生中一半令人沮丧的调试的原因),等等。

而且,如果您要遍历集合的长度,甚至不要这样做。而不是这个:

wordlistLen = len(wlist)
i = 0
while i < wordlistLen:
    # ...
    word = wlist[i]
    # ...
    i = i + 1

... 只需这样做:

for word in wlist:

... 或者,如果您同时需要 iword(您偶尔会这样做):

for i, word in enumerate(wlist):

与此同时,如果您循环访问集合的唯一原因是检查它的每个值,那么您甚至不需要这样做。而不是这个:

wordlistLen = len(wlist)
while i < wordlistLen:
    print wlist[i]
    if newCipher == wlist[i]:
        return newCipher
    else:
        print 'Word not found.'
    i = i + 1

... 只需这样做:

if newCipher in wlist:
    return newCipher
else:
    print 'Word not found.'

在这里,您实际上遇到了一个微妙的错误:您一遍又一遍地打印“未找到单词”,而不是在未找到时只在最后打印一次。

关于使用单词列表的 Python 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712340/

相关文章:

oracle - 如何使用 jaro-winkler 查找表中最接近的值?

python:以灵活的方式处理深度嵌套数据的有效技术是什么?

c# - 如何在 ASP.Net MVC C# 中的 Form Post 上绑定(bind) List<T>

python - 中间合并/连接数据帧以计算统计数据的性能问题

python - 列表中多个最小元素的索引

java - java 8中如何将列表值与另一个列表的索引值进行比较?

python - 将一个字符串与另一个字符串的多个子字符串进行比较

php - 合并两个数组,当前导子字符串相同时用第二个数组值覆盖第一个数组值

python - PCA 用于分类特征?

Python openAL 3D音效