【问题标题】:Explain the syntax of reserved.get(t.value,'ID') in lex.py解释lex.py中reserved.get(t.value,'ID')的语法
【发布时间】:2014-08-18 00:51:34
【问题描述】:

代码取自 ply.lex 文档:http://www.dabeaz.com/ply/ply.html#ply_nn6

reserved = {
   'if' : 'IF',
   'then' : 'THEN',
   'else' : 'ELSE',
   'while' : 'WHILE',
   ...
}

tokens = ['LPAREN','RPAREN',...,'ID'] + list(reserved.values())

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*'
    t.type = reserved.get(t.value,'ID')    # Check for reserved words
    return t

对于reserved这个词,我们需要更改令牌type。通过将t.value 传递给它来执行reserved.get() 是可以理解的。现在它应该返回reserved specification 的第二列中的实体。

但是为什么我们要传递给它ID?是什么意思,解决什么目的?

【问题讨论】:

    标签: parsing python-2.7 tokenize lex lexer


    【解决方案1】:

    第二个参数指定字典中不存在键时要返回的值。所以在这种情况下,如果t.value 的值在reserved 字典中不作为键存在,则将返回字符串'ID'

    换句话说,当a 是一个字典时,a.get(b, c) 大致相当于a[b] if b in a else c(除了它可能更有效,因为它只会在成功的情况下查找一次密钥)。

    请参阅Python documentation for dict.get()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      相关资源
      最近更新 更多