我试图创建类似于密码生成器的东西,第一部分是一个单词,第二部分是一个2位数的数字。但是,每当我运行此程序时,我都会收到索引错误。有解决方案吗?
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')
答案 0 :(得分:2)
当我运行您的代码时,upper_words
和name_words
都是空的。因此,random.randint(0, len(name_words))
总是返回0
,并且代码尝试访问位于0
的索引name_words
处的元素。由于name_words
为空,因此会引发IndexError
。