• 生成器、内置函数、模块与包的使用、正则表达式-day05


    一、生成器

    1、什么是生成器:

      a.生成器函数:只要函数体包含yield关键字,该函数就是生成器函数

      b.生成器就是迭代器。

    2、为什么使用生成器,以及yiled的功能,yield的语句形式: yield 1。

      1)不管函数体中有多少result返回值,return只能返回一次值,函数就终止了。

      2)yiled可以返回多次值,每次返回都会将函数暂停,下一次next会从上一次暂停的位置继续执行。

      3)生成器本身也是迭代器,执行nex方法,进而触发函数的执行。

     1 """
     2     不管函数体中有多少result返回值,return只能返回一次值,函数就终止了。
     3 """
     4 def foo():
     5     return 1
     6     return 2
     7     return 3
     8     return 4
     9 
    10 res1=foo()
    11 print(res1)
    12 
    13 res2=foo()
    14 print(res2)
    15 
    16 """
    17 输出:
    18 1
    19 1
    20 """
    21 
    22 """
    23     yiled可以有多个返回值,生成器本身也是迭代器,使用nex方法执行,进而触发函数的执行
    24 """
    25 def foo():
    26     print('first')
    27     yield 1
    28     print('second')
    29     yield 2
    30     print('third')
    31     yield 3
    32     print('fourth')
    33     yield 4
    34     print('fifth')
    35 #
    36 g=foo()
    37 print(g)   #生成器本身也是迭代器,有next方法
    38 print(next(g)) #触发迭代器g的执行,进而触发函数的执行
    39 print(next(g))
    40 print(next(g))
    41 print(next(g))
    42 #也可以使用for循环执行
    43 # for i in g:
    44 #     print(i)
    45 
    46 """
    47 输出:
    48 <generator object foo at 0x00000000024990A0>       
    49 first
    50 1
    51 second
    52 2
    53 third
    54 3
    55 fourth
    56 4
    57 """

     3、yield的另一种用法,协程函数,yield的表达式形式: x=yield。

     1 """
     2     yiled协程函数,第一次需要传一个空值,再继续传参。
     3     x=yield
     4     g.send('1111'),先把1111传给yield,由yield赋值给x
     5     然后再往下执行,直到再次碰到yield,然后把yield后的返回值返回
     6     yiled后加列表,通过列表,显示每次及之前传入的参数。
     7 """
     8 def deco(func):      #定义装饰器,功能是传空值初始化生成器
     9     def wrapper(*args,**kwargs):
    10         res=func(*args,**kwargs)
    11         next(res)
    12         return res
    13     return wrapper
    14 
    15 @deco
    16 def eater(name):
    17     food_list=[]      #定义空列表
    18     while True:
    19         food=yield food_list   #send传值yiled,yiled赋值给food
    20         food_list.append(food)   #food参数加入到food_list列表
    21         print('%s start to eat %s' %(name,food))
    22 
    23 g=eater('alex')
    24 
    25 # print(g)
    26 # next(g)   #等同于 g.send(None)
    27 #
    28 # g.send('手指头')
    29 # g.send('脚指头')
    30 # g.send('别人的手指头')
    31 # g.send('别人的脚指头')
    32 
    33 """
    34 输出:
    35 <generator object eater at 0x02E75F30>
    36 alex start to eat 手指头
    37 alex start to eat 脚指头
    38 alex start to eat 别人的手指头
    39 alex start to eat 别人的脚指头
    40 """
    41 
    42 print(g)
    43 print(g.send('脚趾头1'))
    44 print(g.send('脚趾头2'))
    45 print(g.send('脚趾头3'))
    46 
    47 """
    48 输出:使用装饰器初始化后,不需要再传空参数,通过使用列表,显示每次及之前传入的参数。
    49 <generator object eater at 0x02B85FC0>
    50 alex start to eat 脚趾头1
    51 ['脚趾头1']
    52 alex start to eat 脚趾头2
    53 ['脚趾头1', '脚趾头2']
    54 alex start to eat 脚趾头3
    55 ['脚趾头1', '脚趾头2', '脚趾头3'
    56 """

    二、模块

    1、自定义文件模块

      可以将一个py文件做为模块导入到当前文件使用其功能。

      a.新建一个spam.py文件

    print('my spam.py')

      b.在当前文件中导入spam模块,执行当前文件,则会执行spam.py文件。

    import spam
    
    """
    输出:
    from spam.py
    """

    2、import导入模块的工作流程。

      1.产生新的名称空间

      2.以新建的名称空间为全局名称空间,执行文件的代码

      3.拿到一个模块名spam,指向spam.py产生的名称空间

     1 """
     2     spam.py
     3 """
     4 money=10
     5 def read1():
     6     print('spam -> read1->',money)
     7 
     8 def read2():
     9     print('spam -> read2->', money)
    10     read1()
    11 
    12 def change():
    13     global money
    14     money=20
     1 """
     2     test.py
     3 """
     4 import spam
     5 money=1000000000000000000000000000000000000000000
     6 print(spam.money)
     7 print(spam.read1)
     8 """
     9 输出:调用spam模块中的函数,格式: 模块名.功能的名字
    10 10
    11 <function read1 at 0x02271978>
    12 """
    13 
    14 spam.read1()   #调用spam模块的read1函数,在新名称空间中
    15 def read1():  #在当前名称空间,定义同名称的read1函数
    16     print('from test.py')
    17 spam.read2()   #调用spam模块中的read2函数,read2中会调用read1
    18 """
    19 输出:spam.read2中调用的仍然是spam中的read1
    20 spam -> read2-> 10
    21 spam -> read1-> 10
    22 """

    3、from ... import ...导入模块的工作流程。

      1.产生新的名称空间

      2.以新建的名称空间为全局名称空间,执行文件的代码

      3.直接拿到就是spam.py产生的名称空间中名字

      4.from ... import ...导入模块的优缺点

        优点:方便,不用加前缀

        缺点:容易跟当前文件的名称空间冲突

     1 # print(money)
     2 # read1()
     3 
     4 # money=10
     5 # del money
     6 # print(money)
     7 
     8 
     9 #
    10 # def read1():
    11 #     print('=========from test.py read1')
    12 # read2()
    13 # import time
    14 # money=100
    15 # print(money)
    16 # time.sleep(200)
    17 #
    18 # read1=10000000
    19 # from spam import read1
    20 # read1()
    21 
    22 
    23 
    24 
    25 # from spam import *
    26 #
    27 # print(money)
    28 # read1()
    29 
    30 
    31 # __all__=['money']
    32 # from spam import *
    33 # print(money)
    34 #
    35 # read1()

    三、包的使用

     1 # import glance
     2 
     3 # glance.api.policy.get()
     4 # print(glance.x)
     5 # print(glance.y)
     6 
     7 # import glance.api.policy
     8 #
     9 # print('===========>')
    10 # glance.api.policy.get()
    11 
    12 
    13 # import glance.api.policy.get #报错,点的左边必须是包
    14 #
    15 # glance.api.policy.get()
    16 
    17 
    18 
    19 # import glance
    20 '''
    21 
    22 from glance.api import policy,versions
    23 from glance.cmd import manage
    24 from glance.db import models
    25 
    26 '''
    27 
    28 # glance.policy.get()
    29 # glance.models.register_models('mysql')
    30 
    31 
    32 # glance.get()
    33 # # glance.register_models('mysql')
    34 
    35 
    36 
    37 
    38 
    39 
    40 
    41 
    42 
    43 
    44 '''
    45 from glance.api.policy import get
    46 from glance.api.versions import create_resource
    47 from glance.cmd.manage import main
    48 from glance.db.models import register_models
    49 '''
    50 # import glance
    51 # # glance.get()
    52 
    53 
    54 
    55 # from glance.api import *
    56 #
    57 # # print(policy)
    58 # # print(versions)
    59 #
    60 # policy.get()
    61 #
    62 #
    63 # import glance.api
    64 #
    65 # glance.api.policy.get()
    66 
    67 
    68 
    69 # import glance
    70 #
    71 #
    72 #
    73 # glance.get()
    74 # glance.register()
    75 
    76 import sys
    77 print(sys)
    78 # import sys
    79 # print(sys.modules)

    四、正则表达式

    1、什么是正则

      正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

    2、python中的正则表达式,re模块

     1 # =================================匹配模式=================================
     2 #正则匹配
     3 import re
     4 #w与W , w匹配字母数字及下划线,W匹配非字母数字及下划线
     5 print(re.findall('w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
     6 print(re.findall('W','hello egon 123')) #[' ', ' ']
     7 
     8 #s与S ,s匹配任意空白字符,等同于[	
    
    f],S匹配任意非空字符
     9 print(re.findall('s','hello  egon  123')) #[' ', ' ', ' ', ' ']
    10 print(re.findall('S','hello  egon  123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
    11 
    12 #d与D,d匹配任意数字,等同于[0-9],D匹配任意非数字
    13 print(re.findall('d','hello egon 123')) #['1', '2', '3']
    14 print(re.findall('D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
    15 
    16 #A与,A匹配字符串开始,匹配字符串结束,如果存在换行,只匹配到换行前的结束字符串
    17 print(re.findall('Ahe','hello egon 123')) #['he'],A==>^
    18 print(re.findall('123','hello egon 123')) #['he'],==>$
    19 
    20 #
    与	,
    匹配一个换行符,	匹配一个制表符
    21 print(re.findall(r'
    ','hello egon 
    123')) #['
    ']
    22 print(re.findall(r'	','hello egon	123')) #['
    ']
    23 
    24 #^与$,^匹配字符串的开头,$匹配字符串的结尾
    25 print(re.findall('^h','hello egon 123')) #['h']
    26 print(re.findall('3$','hello egon 123')) #['3']
    27 
    28 # 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
    29 #. 匹配任意单个字符,除了换行符
    30 print(re.findall('a.b','a1b')) #['a1b']
    31 print(re.findall('a.b','a
    b')) #[]
    32 print(re.findall('a.b','a
    b',re.S)) #['a
    b']
    33 print(re.findall('a.b','a
    b',re.DOTALL)) #['a
    b']同上一条意思一样
    34 
    35 #*  匹配0个或多个前面的表达式
    36 print(re.findall('ab*','bbbbbbb')) #[]
    37 print(re.findall('ab*','a')) #['a']
    38 print(re.findall('ab*','abbbb')) #['abbbb']
    39 
    40 #? 匹配0个或1个前面的表达式
    41 print(re.findall('ab?','a')) #['a']
    42 print(re.findall('ab?','abbb')) #['ab']
    43 #匹配所有包含小数在内的数字
    44 print(re.findall('d+.?d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']
    45 
    46 #.*  匹配任意长度任意字符,默认为贪婪匹配
    47 print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
    48 
    49 #.*? 匹配任意长度任意字符,为非贪婪匹配:推荐使用
    50 print(re.findall('a.*?b','a1b22222222b')) #['a1b']
    51 
    52 #+ 匹配1个或多个前面的表达式
    53 print(re.findall('ab+','a')) #[]
    54 print(re.findall('ab+','abbb')) #['abbb']
    55 
    56 #{n,m} 精确匹配前面的n个表达式
    57 print(re.findall('ab{2}','abbb')) #['abb']
    58 print(re.findall('ab{2,4}','abbb')) #['abb']
    59 print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
    60 print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'
    61 
    62 #[] 匹配其中任意字符
    63 print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
    64 print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
    65 print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
    66 print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
    67 print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']
    68 
    69 ## print(re.findall('a\c','ac')) #对于正则来说a\c确实可以匹配到ac,但是在python解释器读取a\c时,会发生转义,然后交给re去执行,所以抛出异常
    70 print(re.findall(r'a\c','ac')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
    71 print(re.findall('a\\c','ac')) #同上面的意思一样,和上面的结果一样都是['a\c']
    72 
    73 #():分组,匹配括号内的表达式,当有()存在时,只显示()中内容
    74 print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
    75 print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
    76 print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
    77 
    78 # | 或,当()分组存在时,只显示括号里的内容y ies,在前边加?:则可以匹配到company companies
    79 print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
     1 # ===========================re模块提供的方法介绍===========================
     2 import re
     3 #1 参数一为匹配条件,参数二为匹配内容
     4 print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
     5 #2
     6 print(re.search('e','alex make love').group()) #e,直到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
     7 
     8 #3
     9 print(re.match('e','alex make love'))    #None,同search,不过在字符串开始处进行匹配,匹配是否以e开头,如果不是则返回为空,完全可以用search+^代替match
    10 
    11 #4
    12 print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
    13 
    14 #5 参数一为条件,参数二为操作,参数三为操作内容,参数四指定n替换n个
    15 print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有,小写a替换为大写A
    16 print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love ,1只替换第一个
    17 print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love ,2替换两个
    18 print('===>',re.sub('^(w+)(.*?s)(w+)(.*?s)(w+)(.*?)$',r'52341','alex make love')) #===> love make alex
    19 
    20 print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2), re.subn 结果带有总共替换的个数
     1 #例:
     2 
     3 print(re.findall(r'-?d+.?d*',"1-12*(60+(-40.35/5)-(-4*3))")) #找出所有数字['1', '-12', '60', '-40.35', '5', '-4', '3']
     4 #使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,所有即使匹配成功小数也不会存入结果
     5 # 而不是小数时,就去匹配(-?d+),匹配到的自然就是,非小数的数,在此处即整数
     6 print(re.findall(r"-?d+.d*|(-?d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整数['1', '-2', '60', '', '5', '-4', '3']
     7 
     8 ##########
     9 
    10 print(re.findall("<(?P<tag_name>w+)>w+</(?P=tag_name)>","<h1>hello</h1>")) #['h1']
    11 print(re.search("<(?P<tag_name>w+)>w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1>
    12 print(re.search("<(?P<tag_name>w+)>w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1>
    13 
    14 print(re.search(r"<(w+)>w+</(w+)>","<h1>hello</h1>").group())
    15 print(re.search(r"<(w+)>w+</1>","<h1>hello</h1>").group())

    总结:尽量精简,详细的如下:

      尽量使用泛匹配模式 .*

      尽量使用非贪婪模式.*?

      使用括号得到匹配目标:用group(n)去取得结果

      有换行符就用re.S修改模式

  • 相关阅读:
    1.27
    1.25
    Representation Learning with Contrastive Predictive Coding
    Learning a Similarity Metric Discriminatively, with Application to Face Verification
    噪声对比估计(负样本采样)
    Certified Adversarial Robustness via Randomized Smoothing
    Certified Robustness to Adversarial Examples with Differential Privacy
    Dynamic Routing Between Capsules
    Defending Adversarial Attacks by Correcting logits
    Visualizing Data using t-SNE
  • 原文地址:https://www.cnblogs.com/zhangmeixia/p/6930407.html
Copyright © 2020-2023  润新知