获取“IndexError:list index out of range”对我来说没有意义

时间:2017-02-12 14:03:52

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

我根据Gadsby的故事,删除所有标点符号,并将“o”替换为“0”来完成任务。随着故事中的文字,我必须破解一个格式为w1w2w3的PDF并继续上升(w2w3w4,w3w4w5,w4w5w6等),循环直到找到密码。我的问题是我得到一个IndexError:列表索引超出了以下行的范围

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()

1 个答案:

答案 0 :(得分:0)

您正在创建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个单词,就不应该再出现错误