這段代碼是為了從內部文件(文本文件)中選擇一個藝術家,讀取它并從內部文件中隨機選擇藝術家(在數組樣式的文本文件中,例如“胡蘿卜蘋果香蕉”),因此我添加了.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
[]
另一方面,在對行中的數據執行任何操作之前,您似乎要遍歷文本文件中的所有行。這不可能說得通。我建議您隨時將內容添加到列表中,然后從該列表中進行選擇。
添加回答
舉報
0/150
提交
取消