当我试图完成我的项目时,我遇到了一个非常奇怪的错误



这段代码的目的是从内部文件(文本文件(中挑选一位艺术家,读取它并从内部文件中随机挑选艺术家(在数组样式的文本文件中,例如"胡萝卜-苹果-香蕉"(,因此我向所选的艺术家添加了.txt,这样程序就会打开包含歌曲的艺术家文件并随机挑选一首歌曲。

import random
loop = False
counter = 0
points = 0
max_level = 10
while loop == False:
for lines in open("pick.txt").readlines():
art = lines.split()
artist = random.choice(art)
for i in open((artist) + ".txt"):
song = i.split()
song_name = random.choice(song)
print("the song begins with  :" , song_name , "this song is by :" , artist)
answer = input("Enter full name of the song :  ")
if answer == song_name:
points = points +3
print("correct")
counter = counter +1
print(counter)
elif answer != song_name:
print("WRONG !!! n try again")
dec = input("Please enter the full name of the song :")
if dec == song_name:
points = points +2
print("correct")
counter = counter +1
print(counter)
elif dec != song_name:
print("smh n WRONG")
counter = counter +1
print(counter)
elif counter >= max_level:
print("The End")
quit()
else:
print("error")
input()

之后,当我在python shell中运行代码时,我有一个随机的机会出现这个错误,要么直接出现,要么稍后出现:

raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

从外观上看,该错误来自random模块。这可能是在读取文件时,有一行为空。

原因通常是文件的最后一行,通常是空白的换行符/EOF。

只需在读取文件时添加一个复选框:

for line in open(artist + '.txt', 'r'):
if line.strip():
song = line.strip().split()
song_name = random.choice(song)

空行的"truthiness"值为0或False,因此包含内容的行将返回True

您的错误可能是由某个文本文件中的空行引起的。

我能够用你的确切代码和以下文本文件复制你的错误:

pick.txt中只有单词adele,和adele.txt,其中包含来自另一端的hello和两行新行。

你可以在序言中测试这个:

>>> for i in open("adele.txt"):
...     song = i.split()
...
>>> song
[]

另一方面,在对文本文件中的行中的数据执行任何操作之前,您似乎正在对这些行进行迭代。这不可能有意义。我建议你边走边在列表中添加内容,然后从列表中进行选择。

最新更新