以下python代码在标识符中获取错误无效字符。知道为什么吗?我正在编写此函数未完成的函数,由于此错误导致它未运行,因此提早返回None。
def spotifyrecs(mylibrary, newsongs):
total = 0
count = 0
genredict = {}
for artist in mylibrary:
artistsongs = mylibrary[artist]
for adict in artistsongs:
total += adict["plays"]
count += 1
if adict["genre"] not in genredict:
genredict[adict["genre"]] = 1
if adict["genre"] in genredict:
genredict[adict["genre"]] += 1
avgplays = round(total / count, 2)
genrelist = []
for genre in genredict:
newtup = (genredict[genre], genre)
genrelist.append(newtup)
genrelist.sort(reverse = True)
return None
library = {"Ariana Grande": [{"title": "thank u, next", "plays": 100, "genre": "pop"}, {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}], "Khalid":[{"title": "Location", "plays": 15, "genre": "R&B"}, {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}]}
songs = [{"title": "Loving is Easy", "artist": "Rex Orange County", "plays": 115, "genre": "R&B"}, {"title": "Halo", "artist": "Beyonce", "plays": 9, "genre": "R&B"}, {"title": "Focus", "artist": "Ariana Grande", "plays": 112, "genre": "pop"}, {"title": "Winter", "artist": "Khalid", "plays": 800, "genre": "R&B"}]
print(spotifyrecs(library, songs))
错误:
File "so.py", line 22
library = {"Ariana Grande": [{"title": "thank u, next", "plays": 100, "genre": "pop"}, {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}], "Khalid":[{"title": "Location", "plays": 15, "genre": "R&B"}, {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}]}
^
SyntaxError: invalid character in identifier
答案 0 :(得分:1)
您的输入中包含一个非打印字符:除去<200b>字符,即可正常运行。
library = <200b>{
"Ariana Grande": [
{"title": "thank u, next", "plays": 100, "genre": "pop"},
{"title": "Last Christmas", "plays": 44, "genre": "Christmas"}
],
"Khalid":[
{"title": "Location", "plays": 15, "genre": "R&B"},
{"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}
]}
请注意,这有助于很多使程序更具可读性。将其分成几行并进行缩进可以很好地完成两件事:(1)解析器为我提供了更好的位置,因为它可以在行尾发出错误消息; (2)通过这种方式,我可以更轻松地找到简单的错字和括号平衡。