为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

江户川乱折腾 2021-08-14 13:44:37
这段代码是为了从内部文件(文本文件)中选择一个艺术家,读取它并从内部文件中随机选择艺术家(在数组样式的文本文件中,例如“胡萝卜苹果香蕉”),因此我添加了.txt 到所选艺术家,以便程序将打开带有歌曲的艺术家文件并随机选择一首歌曲。import randomloop = Falsecounter = 0points = 0max_level = 10while 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 NoneIndexError: Cannot choose from an empty sequence
查看完整描述

2 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

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


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


pick.txt 只包含单词 adele,而 adele.txt 包含 hello-from-the-other-side 和两个新行。


您可以在前奏中对此进行测试:


>>> for i in open("adele.txt"):

...     song = i.split()

...

>>> song

[]

另一方面,在对行中的数据执行任何操作之前,您似乎要遍历文本文件中的所有行。这不可能说得通。我建议您随时将内容添加到列表中,然后从该列表中进行选择。


查看完整回答
反对 回复 2021-08-14
  • 2 回答
  • 0 关注
  • 340 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号