【问题标题】:Is it possible to get a list of keywords in Python?是否可以在 Python 中获取关键字列表?
【发布时间】:2012-03-09 22:55:22
【问题描述】:

我想获取所有 Python 关键字作为字符串的列表。如果我可以为内置函数做类似的事情,那也是相当不错的。

类似这样的:

import syntax
print syntax.keywords
# prints ['print', 'if', 'for', etc...]

【问题讨论】:

标签: python list syntax


【解决方案1】:

您询问了语句,同时在输出示例中显示了关键字

如果您正在寻找关键字,它们都列在keyword 模块中:

>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
 'while', 'with', 'yield']

来自keyword.kwlist doc

包含为解释器定义的所有关键字的序列。如果任何关键字被定义为仅在特定 __future__ 语句生效时才有效,那么这些关键字也将被包括在内。

【讨论】:

  • 内置函数是NOT 语句statement 是当您进行声明时,例如定义一个函数并以 keyword def 开头并具有一个或多个子句等。他询问了 内置标识符与您指出的语句无关。从他的输出来看,只有iffor关键字print 只是一个内置标识符。此外,该示例并不完整,因为您只列出了 keywords 而没有按照他的要求列出 built-in identifiers (functions)。我认为你应该修改答案以包括那些。
  • 此外,如果您希望答案完整,您应该使答案更加精细,因为printPython2Python3 中的含义不同乙>。在 Python3 中,它不会像在您的示例中那样显示,因为正如我在上述答案中指出的那样,它不再是 keyword (而只是 keyword b>内置标识符)。另外,由于他询问了内置的函数,因此需要包含these。现在,我知道这个帖子已经存在了很长一段时间,但这可能会对未来的读者有所帮助。
  • 为什么newinit、self、cls等都不见了,怎么也列出来?
【解决方案2】:

内置函数在一个名为__builtins__的模块中,所以:

dir(__builtins__)

【讨论】:

  • 如果这段代码在一个导入的模块中,我认为应该是__builtins__.keys()。或者在 Python 3 中,import builtins 然后是 dir(builtins),无论模块如何。 docs.python.org/3/reference/executionmodel.html "默认情况下,在__main__ 模块中,__builtins__ 是内置模块builtins;在任何其他模块中,__builtins__builtins 模块本身的字典的别名。”
【解决方案3】:

我能想到的最接近的方法如下:

from keyword import kwlist
print kwlist

标准的keyword 模块是自动生成的。有关从 Python 解析 Python 的其他内容,请查看 language services 模块集。

关于列出内置函数,我不清楚您是要查找 __builtin__ 模块中的项目还是该包中直接在 CPython 解释器中实现的函数:

import __builtin__ as B
from inspect import isbuiltin

# You're either asking for this:
print [name for name in dir(B) if isbuiltin(getattr(B, name))]

# Or this:
print dir(B)

【讨论】:

    【解决方案4】:

    或者你可以importbuiltins:

    >>> import builtins
    >>> dir(builtins)
    ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
    >>> 
    

    OR(这不包含错误和旁边有__的东西):

    >>> help('keywords')
    
    Here is a list of the Python keywords.  Enter any keyword to get more help.
    
    False               def                 if                  raise
    None                del                 import              return
    True                elif                in                  try
    and                 else                is                  while
    as                  except              lambda              with
    assert              finally             nonlocal            yield
    break               for                 not                 
    class               from                or                  
    continue            global              pass                
    

    【讨论】:

      【解决方案5】:

      >>> help()

      帮助>关键字

      这里是 Python 关键字的列表。输入任何关键字以获得更多帮助。

      False def if raise

      None del import return

      True elif in try

      and else is while

      as except lambda with

      assert finally nonlocal yield

      break for not

      class from or

      continue global pass

      【讨论】:

        【解决方案6】:

        获取所有 Python 关键字的列表

        • 2018-06-07

        自动生成标准关键字模块(Quine) Quine (computing)

        >>> import keyword
        >>> keyword.kwlist
        ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
        >>> len(keyword.kwlist)
        33
        

        我对关键字进行了分类以供进一步参考。

        keywords_33=[
            ('file_2', ['with', 'as']),
            ('module_2', ['from', 'import']),
            ('constant_3', {'bool': ['False', 'True'], 
                            'none': ['None']}),
            ('operator_5',
                    {'logic': ['and', 'not', 'or'],
                    'relation': ['is', 'in']}),
            ('class_1', ['class']),
            ('function_7',
                    ['lambda','def','pass',
                    'global','nonlocal',
                    'return','yield']),
            ('loop_4', ['while', 'for', 'continue', 'break']),
            ('condition_3', ['if', 'elif', 'else']),
            ('exception_4', ['try', 'raise','except', 'finally']),
            ('debug_2', ['del','assert']),
        ]
        

        【讨论】:

          【解决方案7】:

          你不需要导入语法,但你仍然需要导入关键字。

          >>> import keyword
          >>> print(keyword.kwlist)
          

          结果是:

          ['False', 'None', 
          'True', 'and', 'as', 'assert', 
          'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 
          'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 
          'raise', 'return', 'try', 'while', 'with', 'yield']
          

          【讨论】:

            猜你喜欢
            • 2022-01-10
            • 2019-01-30
            • 1970-01-01
            • 1970-01-01
            • 2015-11-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多