简体   繁体   中英

AttributeError: 'list' object has no attribute 'split' - Python Progject

Need help with my code, trying to create a music game. I am getting a 'AttributeError: 'list' object has no attribute 'split'. Help would be appreciated.

Thanks

 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.") 

Please refer also to this question: Attribute Error: 'list' object has no attribute split

From this you can see that split is an attribute of strings not lists! The solution from the above question was to split each string/line of the list, so use something like:

songs = [sentence.split() for sentence in songs]

To be clear here, sentence is an arbitrary iterator and can be named more appropriately (eg like verse) for your purpose. Even though it does not matter to the code execution, good naming is always helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM