2014-04-04 19 views
100

Python ayrılmış sözcükler ve yerleşimler kütüphanede var mı? Ben böyle bir şey yapmak istiyorum: bir dize sen keyword.iskeyword kullanabileceğiniz bir anahtar kelime olduğunu doğrulamak içinPython ayrılmış sözcükler ve yerleşimler kütüphanede var mı?

from x.y import reserved_words_and_builtins 

if x in reserved_words_and_builtins: 
    x += '_' 
+0

olası yinelenen (http://stackoverflow.com/questions/14595922/list-of-python-keywords) – Abhijit

+2

@Abhijit __builtin__ modülünü kullanmak gerekir Yerleşik dahil olmak üzere tüm ayrılmış sözcükleri sordum. –

+0

düzenleme: görünüşte birçok kişi anahtar kelime ile eş anlamlı olmaya "ayrılmış kelime" kullanın. Soruyu buna göre düzenledim. –

cevap

140

; Ardından, dahil etmek istiyorsanız yerleşik yanı (Python 3) adlarında

>>> import keyword 
>>> keyword.iskeyword('break') 
True 
>>> 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'] 

,: Eğer keyword.kwlist kullanabilirsiniz ayrılmış anahtar kelimelerin listesini almak için Python 2 olacak İçin

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

temel fark inci geçerli:

>>> import __builtin__ 
>>> dir(__builtin__) 
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] 
[piton anahtar kelimelerin Listesi]
+9

Not: python2.6 <= xy <3.0 'Yok' * * * biçimsel olarak bir anahtar kelime (' kwlist' ve 'iskeyword''na göre) ancak aslında * bir anahtar sözcüktür (çünkü' None = 1' ile başarısız olur) "SyntaxError"), "True" ve "False" ile birlikte yerleşik olarak listelenmesine rağmen. – Bakuriu

+2

Sadece meraktan, anahtar kelimeler ve yerleşikler arasında bir ayrım yapmak için felsefi gerekçe nedir? Onların hepsi sadece rezerve edilmemeli mi? – notconfusing

+6

@notconfusing: anahtar kelimeler, dilin dilbilgisinin bir parçasıdır. Yerleşikler, “builtins import *” den yapmış gibi davranırlar; onlar geçersiz kılınabilir. –

İlgili konular