是否有可能在Python中获取关键字列表?

时间:2012-03-09 22:55:22

标签: python list syntax

我想将所有Pythons关键字列表作为字符串。如果我能为内置函数做类似的事情,那也会很有趣。

这样的事情:

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

7 个答案:

答案 0 :(得分:63)

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

如果您正在寻找关键字,则会在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__语句生效时才处于活动状态,那么这些关键字也将被包括在内。

答案 1 :(得分:9)

内置函数位于名为__builtins__的模块中,因此:

dir(__builtins__)

答案 2 :(得分:5)

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

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)

答案 3 :(得分:2)

或者您可以import builtins

>>> 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                

答案 4 :(得分:0)

>>> 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

答案 5 :(得分:0)

  

获取所有Pythons关键字的列表

  • 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']),
]

答案 6 :(得分:0)

您无需导入语法,但仍必须导入关键字。

>>> 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']