标识符中的无效字符

新手上路,请多包涵

我正在处理 HP code wars 2012 中的字母分布问题。我不断收到一条错误消息,提示“标识符中的字符无效”。这是什么意思,如何解决?

是包含信息的页面。

 import  string

def  text_analyzer(text):
'''The text to be parsed and
the number of occurrences of the letters given back
be. Punctuation marks, and I ignore the EOF
simple. The function is thus very limited.

'''
    result =  {}

# Processing
    for  a in  string.ascii_lowercase:
    result [a] =  text.lower (). count (a)

    return  result

def  analysis_result (results):

# I look at the data
    keys =  analysis.keys ()
    values \u200b\u200b=  list(analysis.values \u200b\u200b())
    values.sort (reverse = True )

# I turn to the dictionary and
# Must avoid that letters will be overwritten
    w2 =  {}
    list =  []

    for  key in  keys:
        item =  w2.get (results [key], 0 )
        if  item = =  0 :
            w2 [analysis results [key]] =  [key]
        else :
            item.append (key)
            w2 [analysis results [key]] =  item

# We get the keys
    keys =  list (w2.keys ())
    keys.sort (reverse = True )

    for  key in  keys:
        list =  w2 [key]
        liste.sort ()
        for  a in  list:
            print (a.upper (), "*"  *  key)


text =  """I have a dream that one day this nation will rise up and live out the true
meaning of its creed: "We hold these truths to be self-evident, that all men
are created equal. "I have a dream that my four little children will one day
live in a nation where they will not be Judged by the color of their skin but
by the content of their character.
# # # """

analysis result =  text_analyzer (text)
analysis_results (results)

原文由 user2052898 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 711
1 个回答

错误 SyntaxError: invalid character in identifier 意味着变量名、函数等中间有一些字符,不是字母、数字或下划线。实际的错误消息看起来像这样:

   File "invalchar.py", line 23
    values =  list(analysis.values ())
                ^
SyntaxError: invalid character in identifier

这告诉您实际问题是什么,所以您不必猜测“我在哪里有无效字符”?好吧,如果你看那一行,你会发现里面有一堆非打印垃圾字符。把它们拿出来,你就会过去的。

如果您想知道实际的垃圾字符是什么,我从您的代码中复制了违规行并将其粘贴到 Python 解释器中的字符串中:

 >>> s='    values ​​=  list(analysis.values ​​())'
>>> s
'    values \u200b\u200b=  list(analysis.values \u200b\u200b())'

所以,那是 \u200b ,或 零宽度空间。这就解释了为什么您在页面上看不到它。最常见的是,您获得这些是因为您从 StackOverflow 或 wiki 等网站或 PDF 文件复制了一些格式化(非纯文本)代码。

如果您的编辑器没有为您提供查找和修复这些字符的方法,只需删除并重新键入该行。

当然你也有至少两个 IndentationError s 从不缩进的东西,至少一个 SyntaxError 来自停留空间(比如 = = == ef2 --- )或下划线变成空格(如 analysis results 而不是 analysis_results )。

问题是,你是如何让你的代码进入这种状态的?如果您使用 Microsoft Word 之类的软件作为代码编辑器,那就是您的问题了。使用文本编辑器。如果不是……好吧,不管是什么根本问题导致您最终出现这些垃圾字符、损坏的缩进和多余的空格,请在尝试修复代码之前修复它。

原文由 abarnert 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题