需要帮助我的代码,以尝试创建音乐游戏。我收到一个'AttributeError:'list'对象没有属性'split'。帮助将不胜感激。
谢谢
import random
read = open("Songs.txt", "r")
songs = read.readlines()
songlist = []
#readlines - https://stackoverflow.com/questions/38105507/when-should-i-ever-use-file-read-or-file-readlines
for i in range(len(songs)):
songlist.append(songs[i].strip('\n'))
songname = random.choice(songlist)
#https://pynative.com/python-random-choice/ - random choice
songs = songs.split()
letters = [word[0] for word in songs]
firstguess = input("Please enter your first guess for the name of the song.")
if firstguess is True:
print("Well done, you have been awarded 3 points.")
elif firstguess is False:
print("Unlucky, that answer is incorrect. Please try again to win 1 point.")
secondguess = input("Please enter your second guess for the name of the song. Last try, make sure to think before typing!")
if secondguess is True:
print("Well done, you managed to clutch 1 point.")
elif secondguess is False:
print("Unlucky, maybe you will know the next song.")
答案 0 :(得分:1)
也请参考以下问题:Attribute Error: 'list' object has no attribute split
由此您可以看到split
是字符串而不是列表的属性!上述问题的解决方案是拆分列表的每个字符串/行,因此使用类似以下内容的
songs = [sentence.split() for sentence in songs]
此处要清楚,sentence
是一个任意的迭代器,可以根据您的目的更恰当地命名(例如verse)。即使对代码执行无关紧要,但良好的命名总是有帮助的。