【问题标题】:Getting an "IndexError: list index out of range" that does not make sense to me得到一个对我没有意义的“IndexError:列表索引超出范围”
【发布时间】:2017-06-30 12:29:28
【问题描述】:

我有一个作业要做,该作业的基础是讲述 Gadsby 的故事,删除所有标点符号,并将“o”替换为“0”。使用故事中的文字,我必须破解一个格式为 w1w2w3 的 PDF,并不断循环上升(w2w3w4、w3w4w5、w4w5w6 等),直到找到密码。我的问题是我得到一个 IndexError: list index out of range on the following line

password = word_list[list_1] + word_list[list_2] + word_list[list_3]

非常感谢您帮助找出错误的原因,因为我过去 2 天一直在查看它,但无济于事。如果您发现我的代码中还有任何其他错误,请同时指出。

import re
import PyPDF2

# Defining the function called "pdf_cracker"
def pdf_cracker():
    # Import the shuffle
`   from random import shuffle
    # Open Gadsby story and define it as the variable "string"
    string = open("gadsby.txt", "r").read()
    # Uses substitution in the RE module to only include characters from a-z, A-Z and 0-9
    new_str = re.sub("[^a-zA-Z0-9]", " ",string)
    open("gadsby_no_punctuation.txt", "w").write(new_str)
    gadsby_no_punctuation = open("gadsby_no_punctuation.txt", "r").read().split()

    word_list = [gadsby_no_punctuation]

    list_1 = 0
    list_2 = 1
    list_3 = 2


for item in word_list:          
    password = word_list[list_1] + word_list[list_2] + word_list[list_3] # ERROR ON THIS LINE
    password = password.replace("o", "0")
    password = password.replace("O", "0")
    print password

    from PyPDF2 import PdfFileReader, PdfFileWriter
    pdf_file = ("crack_me.pdf", "rb")

    if pdf.isEncrypted == False:
        print "The file you're trying to crack doesn't have a password"

    if(pdf_file.decrypt(password) == 1):
        print "O " + password + " is the password!"
        break

    else:       
        print "X " + password + " is not the password"
        list_1 = list_1 + 1
        list_2 = list_2 + 1
        list_3 = list_3 + 1

if __name__ == "__main__":
    zip_cracker() # Ignore this line - this is another part of the program, not throwing up any errors.
    pdf_cracker()

【问题讨论】:

  • 您每次都分配 5 个。签出:pythontutor.com
  • 我认为这是正在发生的事情
  • 我是吗?哪里有?
  • 查看链接是否有帮助

标签: python-2.7 list loops pdf for-loop


【解决方案1】:

您正在创建 gadsby 列表,然后将其放入另一个列表中

gadsby_no_punctuation = "a b c d e f g".split() # A test string
>>> gadsby_no_punctuation
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> word_list = [gadsby_no_punctuation]
>>> word_list
[['a', 'b', 'c', 'd', 'e', 'f', 'g']] # a list inside a list
>>> len(word_list)
1 # only 1 item in the list

代替

word_list = [gadsby_no_punctuation]

使用 [:] 复制 gadsby 列表

word_list = gadsby_no_punctuation[:]

只要至少有 3 个单词,就不会再出现该错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多