GVKun编程网logo

是否可以获取Python中的关键字列表?(如何获取python关键字)

14

针对是否可以获取Python中的关键字列表?和如何获取python关键字这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展'file'是python中的关键字吗?、id是python中的关键字

针对是否可以获取Python中的关键字列表?如何获取python关键字这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展'file'是python中的关键字吗?、id是python中的关键字吗?、Python - 检查列表中的关键字是否在字符串中(作为一个整体)并返回找到的关键字、python3 中的关键字等相关知识,希望可以帮助到你。

本文目录一览:

是否可以获取Python中的关键字列表?(如何获取python关键字)

是否可以获取Python中的关键字列表?(如何获取python关键字)

我想获取所有Pythons关键字作为字符串的列表。如果我可以为内置函数做类似的事情,那也将很漂亮。

像这样的东西:

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

答案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文档:

包含为解释程序定义的所有关键字的序列。如果将任何关键字定义为仅在特定__future__语句生效时才处于活动状态,则这些关键字也将包括在内。

'file'是python中的关键字吗?

'file'是python中的关键字吗?

filepython中的关键字吗?

我看过一些使用关键字的代码file就很好,而其他人则建议不要使用它,而我的编辑器则将其作为关键字进行颜色编码。

答案1

小编典典

不,file是内置的,不是关键字:

>>> import keyword>>> keyword.iskeyword(''file'')False>>> import __builtin__>>> hasattr(__builtin__, ''file'')True

可以将其视为的别名open(),但是由于新io框架替代了它,因此已从Python
3中删除了它。从技术上讲,它是函数返回的对象open()的类型。

id是python中的关键字吗?

id是python中的关键字吗?

如何解决id是python中的关键字吗??

| 我的编辑器(TextMate)以其他颜色(当用作变量名时)显示)0ѭ,而不是通常的变量名。是关键字吗?我不想给任何关键字加上阴影...     

解决方法

        
id
不是Python中的关键字,而是内置函数的名称。 关键字是:
and       del       from      not       while
as        elif      global    or        with
assert    else      if        pass      yield
break     except    import    print
class     exec      in        raise
continue  finally   is        return
def       for       lambda    try
关键字是无效的变量名。以下是语法错误:
if = 1
另一方面,诸如
id
type
str
之类的内置函数可能会被遮盖:
str = \"hello\"    # don\''t do this
    ,        您还可以从python获得帮助:
>>> help(id)
Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it\''s the object\''s memory address.)
或者,您可以质疑IPython
IPython 0.10.2   [on Py 2.6.6]
[C:/]|1> id??
Type:           builtin_function_or_method
Base Class:     <type \''builtin_function_or_method\''>
String Form:    <built-in function id>
Namespace:      Python builtin
Docstring [source file open failed]:
    id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it\''s the object\''s memory address.)
    ,        仅供参考: 检查Python中是否有关键字:
>>> import keyword  
>>> keyword.iskeyword(\''id\'')
False
检查Python中的所有关键字:
>>> 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\'']
    ,        这是一个内置函数:
id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it\''s the object\''s memory address.)
    

Python - 检查列表中的关键字是否在字符串中(作为一个整体)并返回找到的关键字

Python - 检查列表中的关键字是否在字符串中(作为一个整体)并返回找到的关键字

这是使用 regex 的一种方法:

import re

keywords = [
    "FDA","Contract","Vaccine","Efficacy","SARS","COVID-19","Cancer","Exclusive","Explosive","Hydrogen","Positive","Phase"
]

titles = [
    "Global Water and Sewage Market Report (2021 to 2030) - COVID-19 Impact and Recovery","Blackbaud CEO Mike Gianoni Named One of 50 Most Influential by Charleston Business Magazine","Statement from Judy R. McReynolds on Signing of HR1319,the American Rescue Plan Act of 2021",]

pattern = '|'.join(f"\\b{k}\\b" for k in keywords)  # Whole words only                                                      
matches = {k: 0 for k in keywords}
for title in titles:
    for match in re.findall(pattern,title):
        matches[match] += 1
,

您可以遍历列表并使用 'in' 运算符,我们可以检查它是否存在于字符串中:

strings = ["Global Water and Sewage Market Report (2021 to 2030) - COVID-19 Impact and Recovery",the American Rescue Plan Act of 2021"]

keywords = [
    "FDA","Phase"
]

article_keywords = {}

for string in strings:
    for word in keywords:
        if word in string:
            article_keywords[string] = word
            break

print(article_keywords)

在字典(article_keywords)中,键是字符串,值是找到的第一个关键字。

python3 中的关键字

python3 中的关键字

The following identifiers are used as reserved words, or  keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
 
  1. False      class      finally    is         return
  2. None       continue   for        lambda     try
  3. True       def        from       nonlocal   while
  4. and        del        global     not        with
  5. as         elif       if         or         yield
  6. assert     else       import     pass       break
  7. except     in         raise
共 33 个。
Flase  布尔类型的值,标示假,和 True 相反
class  定义类的关键字
finally 在异常处理的时候添加,有了它,程序始终要执行 finally 里面的程序代码块,如:
 
  1. class MyException(Exception):passtry:
  2.     #some code here
  3.     raise MyExceptionexcept MyException:
  4.     print "MyException encoutered"finally:
  5.     print "Arrive finally"
is  Python 中的对象包含三要素:id、type、value
其中 id 用来唯一标识一个对象,type 标识对象的类型,value 是对象的值
is 判断的是 a 对象是否就是 b 对象,是通过 id 来判断的
== 判断的是 a 对象的值是否和 b 对象的值相等,是通过 value 来判断的
 
  1. >>> a = 1
  2. >>> b = 1.0
  3. >>> a is b
  4. False
  5. >>> a == b
  6. True
  7. >>> id(a)12777000
  8. >>> id(b)14986000
return  return 语句用来从一个函数 返回 即跳出函数。我们也可选从函数 返回一个值 
None None 是一个特殊的常量。None 和 False 不同。None 不是 0。None 不是空字符串。None 和任何其他的数据类型比较永远返回 False。None 有自己的数据类型 NoneType。你可以将 None 复制给任何变量,但是你不能创建其他 NoneType 对象
 
  1. >>> type(None) <class ''NoneType''>  
  2. >>> None == 0  
  3. False
  4. >>> None == ''''  
  5. False
  6. >>> None == None  
  7. True
  8. >>> None == False  
  9. False
continue  continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后 继续 进行下一轮循环。
for  for..in 是另外一个循环语句,它在一序列的对象上 递归 即逐一使用队列中的每个项目
lambda 匿名函数是个很时髦的概念,提升了代码的简洁程度。如:
  1. g = lambda x: x*2 
  2. g(3)
try  我们可以使用 try..except 语句来处理异常。我们把通常的语句放在 try - 块中,而把我们的错误处理语句放在 except - 块中。
True  布尔类型的值,标示真,和 False 相反
def  # 定义函数
  1. def hello():
  2.     print(''hello,hongten'')
  3.     # 调用函数        hello ()
  4.     >>> hello,hongten
from  在 python 用 import 或者 from...import 来导入相应的模块
nonlocal  nonlocal 关键字用来在函数或其他作用域中使用外层 (非全局) 变量,如:
  1. def make_counter():
  2.     count = 0
  3.     def counter():
  4.         nonlocal count
  5.         count += 1
  6.         return count
  7.     return counter
  8.     def make_counter_test():
  9.   mc = make_counter()
  10.  print(mc())
  11.  print(mc())
  12.  print(mc())
while  while 语句允许你重复执行一块语句。while 语句是所谓 循环 语句的一个例子。while 语句有一个可选的 else 从句。
and 逻辑判断和 C 的 && 一样
del del 用于 list 列表操作,删除一个或者连续几个元素。如:
  1. a = [-1, 3,''aa'', 85] # 定义一个 list
  2. del a[0] #删除第 0 个元素
  3. del a[2:4] #删除从第 2 个元素开始,到第 4 个为止的元素。包括头不包括尾 
global  定义全局变量
not  逻辑判断和 C 的!一样
with  with 是 python2.5 以后才有的,它实质是一个控制流语句,with 可以用来简化 try-finally 语句。它的主要用法是实现一个类__enter__()和__exit__() 方法,如:
 
  1. class controlled_execution:
  2.     def _enter__(self):
  3.         set things up
  4.         return thing
  5.     def __exit__(self, type, value,  traceback):
  6.         tear thing down
  7. with controlled_execution() as thing:
  8.     some code
as  结合 with 使用
elif  和 if 配合使用的
if  if 语句用来检验一个条件, 如果 条件为真,我们运行一块语句(称为 if - 块 ), 否则 我们处理另外一块语句(称为 else - 块 )。 else 从句是可选的。
or   逻辑判断和 C 的 || 一样
yield yield 是关键字, 用起来像 return,yield 在告诉程序,要求函数返回一个生成器,如:
  1. def createGenerator() :
  2. mylist = range(3)for i in mylist :yield i*i
assert 断言,这个关键字用来在运行中检查程序的正确性,和很多其他语言是一样的作用。如:
  1. assert len(mylist) >= 1  
else  
import  在 python 用 import 或者 from...import 来导入相应的模块,如:
  1. from sys import *print(''path:'',path)
pass  pass 的意思是什么都不要做,作用是为了弥补语法和空定义上的冲突,我理解他的好处体现在代码的编写过程之中,比如你可以先写好软件的整个框架,然后再填好框架内具体函数和 class 的内容,如果没有 pass 编译器会报一堆的错误,让整个开发过程很不流畅,如:
  1. def f(arg): pass    # a function that does nothing (yet)
  2. class C: pass       # a class with no methods (yet)
break  
break 语句是用来 终止 循环语句的,即哪怕循环条件没有称为 False 或序列还没有被完全递归,也停止执行循环语句。
一个重要的注释是,如果你从 for 或 while 循环中 终止,任何对应的循环 else 块将不执行。
except  使用 try 和 except 语句来捕获异常
in  for..in 是另外一个循环语句,它在一序列的对象上 递归 即逐一使用队列中的每个项目
raise python raise 和 java  throw 很类似,都是抛出异常。如:
 
  1. class MyException(Exception):passtry:
  2.     #some code here
  3.     raise MyExceptionexcept MyException:
  4.     print "MyException encoutered"finally:
  5.     print "Arrive finally"

 

关于是否可以获取Python中的关键字列表?如何获取python关键字的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于'file'是python中的关键字吗?、id是python中的关键字吗?、Python - 检查列表中的关键字是否在字符串中(作为一个整体)并返回找到的关键字、python3 中的关键字的相关信息,请在本站寻找。

本文标签: