0

我试图创建类似于密码生成器的东西,第一部分是一个单词,第二部分是一个两位数。但是,每当我运行这个程序时,我都会收到一个索引错误。有什么解决办法吗?


import urllib.request
import random



word_url = "https://donyinc.weebly.com/uploads/4/2/1/7/42178775/part1.txt"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
one_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(1)])


def rand_name():
   name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(1)])
   return name


for n in range(10):
    name = rand_name()

#part 2

alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@#$%^&*"
no_length = 2
myno = ""

for i in range(no_length):
    next_index = random.randrange(len(alphabet))
    myno = myno + alphabet[next_index]

print(name)+(no)

input('Press ENTER to exit')

4

1 回答 1

2

当我运行你的代码时,两者upper_words都是name_words空的。因此,random.randint(0, len(name_words))总是返回0,并且代码尝试访问索引0为的元素name_words。因为name_words是空的,所以这会引发一个IndexError.

于 2019-02-10T22:00:30.520 回答