这是我的代码:
def MusicGame():
score=0
tries = 0
with open("songs.txt") as file:
for line in file.readlines():
artist,name=line.split(" - ", 1)
question=(artist + "- " + " ".join([x[0].upper() for x in name.split()])+": ")
answer=input(question)
if tries != 2:
if answer in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
print("well done")
tries=0
score=score+3
elif answer not in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
answer2=input("it was wrong try again")
if answer in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
print("well done+1")
tries=tries+1
score=score+1
elif answer2 not in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
print("you suck you lost")
break
我不断收到此错误
artist,name=line.split(" - ", 1)
ValueError: need more than 1 value to unpack
我的文本文件如下:
6ix9ine,Bobby Shmurda-STOOPID
戴夫,弗雷多-时髦的星期五
Trippie Redd,Travis Scott-Dark Knight Dummo
NSG-自然灾害
打气筒-Gucci Gang
答案 0 :(得分:0)
您的文件似乎有空行。您无法将'-'
上的内容拆分成两个变量,因为这些行不包含该字符。首先过滤掉空行。
演示:
>>> def non_blank(file):
... return (line for line in file if line.strip())
...
>>> with open('songs.txt') as songs:
... for line in non_blank(songs):
... print(line.split(' - '))
...
['6ix9ine,Bobby Shmurda', 'STOOPID\n']
['Dave,Fredo', 'Funky Friday\n']
['Trippie Redd,Travis Scott', 'Dark Knight Dummo\n']
['NSG', 'Natural Disaster\n']
['Lil pump', 'Gucci Gang\n']