【问题标题】:Python Invalid Character in IdentifierPython标识符中的无效字符
【发布时间】:2018-12-03 17:33:39
【问题描述】:

下面的 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

【问题讨论】:

  • 不要让我们找到错误在哪里。你得到这个是什么行号?
  • 它没有告诉我什么行号
  • 发现有语法错误,但我知道,在底部的库行中,它指向'Broke'的'e'

标签: python identifier


【解决方案1】:

您的输入中有一个非打印字符:去掉 字符,这运行得很好。

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) 通过这种方式,我可以更轻松地查找简单的拼写错误和括号平衡。

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 2013-01-28
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多