我在尝试完成我的项目时遇到非常奇怪的错误

这段代码是为了从内部文件(文本文件)中选择一个艺术家,读取它并从内部文件中随机选择艺术家(在数组样式的文本文件中,例如“胡萝卜苹果香蕉”),因此我添加了.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


江户川乱折腾
浏览 341回答 2
2回答

慕村225694

您的错误可能是由您的文本文件之一中的空行引起的。我能够用您的确切代码和以下文本文件复制您的错误:pick.txt 只包含单词 adele,而 adele.txt 包含 hello-from-the-other-side 和两个新行。您可以在前奏中对此进行测试:>>> for i in open("adele.txt"):...     song = i.split()...>>> song[]另一方面,在对行中的数据执行任何操作之前,您似乎要遍历文本文件中的所有行。这不可能说得通。我建议您随时将内容添加到列表中,然后从该列表中进行选择。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python