• Python基础第15天


                                                                                   常用模块(二)

    一:re模块

    就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

    字符匹配(普通字符,元字符):

    1 普通字符:大多数字符和字母都会和自身匹配
                  >>> re.findall('alvin','yuanaleSxalexwupeiqi')
                          ['alvin'] 

    2 元字符:. ^ $ * + ? { } [ ] | ( )

    .   通配符

    ^  以、、开头匹配

    $  以、、结尾匹配

    * + ? { }  重复字符    *匹配(0,无穷)次;+匹配(1,无穷)次;?匹配(0,1)次 ;{}匹配以上所有情况

    [ ]  中没有特殊字符,都是普通字符,除 —  ^      外

    [a-z]表示a-z范围内所有字符,[^a-z] 表示除a-z以外所有匹配出来, 表示转义:

    反斜杠后边跟元字符去除特殊功能,比如.
    反斜杠后边跟普通字符实现特殊功能,比如d

    d  匹配任何十进制数;它相当于类 [0-9]。
    D 匹配任何非数字字符;它相当于类 [^0-9]。
    s  匹配任何空白字符;它相当于类 [ fv]。
    S 匹配任何非空白字符;它相当于类 [^ fv]。
    w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
    W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
      匹配一个特殊字符边界,比如空格 ,&,#等

    一一举例:

    import re
     
    ret=re.findall('a..in','helloalvin')
    print(ret)#['alvin']
     
     
    ret=re.findall('^a...n','alvinhelloawwwn')
    print(ret)#['alvin']
     
     
    ret=re.findall('a...n$','alvinhelloawwwn')
    print(ret)#['awwwn']
     
     
    ret=re.findall('a...n$','alvinhelloawwwn')
    print(ret)#['awwwn']
     
     
    ret=re.findall('abc*','abcccc')#贪婪匹配[0,+oo]  
    print(ret)#['abcccc']
     
    ret=re.findall('abc+','abccc')#[1,+oo]
    print(ret)#['abccc']
     
    ret=re.findall('abc?','abccc')#[0,1]
    print(ret)#['abc']
     
     
    ret=re.findall('abc{1,4}','abccc')
    print(ret)#['abccc'] 贪婪匹配
    注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配
    
    ret=re.findall('abc*?','abcccccc')
    print(ret)#['ab']

    字符集:

    #--------------------------------------------字符集[]
    ret=re.findall('a[bc]d','acd')
    print(ret)#['acd']
     
    ret=re.findall('[a-z]','acd')
    print(ret)#['a', 'c', 'd']
     
    ret=re.findall('[.*+]','a.cd+')
    print(ret)#['.', '+']
     
    #在字符集里有功能的符号: - ^ 
     
    ret=re.findall('[1-9]','45dha3')
    print(ret)#['4', '5', '3']
     
    ret=re.findall('[^ab]','45bdha3')
    print(ret)#['4', '5', 'd', 'h', '3']
     
    ret=re.findall('[d]','45bdha3')
    print(ret)#['4', '5', '3']

    综合的一个例子:

    import re
    re.findall('([^()]*)','12+(34*6+2-5*(3-4))')
    ['(3-4)']
    关于“r”加与不加
    ret=re.findall('I','I am LIST') print(ret)#[] ret=re.findall(r'I','I am LIST') print(ret)#['I'] import re ret=re.findall('cl','abcle') print(ret)#[] ret=re.findall('c\l','abcle') print(ret)#[] ret=re.findall('c\\l','abcle') print(ret)#['c\l'] ret=re.findall(r'c\l','abcle') print(ret)#['c\l']

    元字符之分组:

    re.search()   #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以

            # 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
    re.match()   同search ,不过仅可以从开头匹配
    re.split()    分割
    举例:
    m = re.findall(r'(ad)+', 'add')
    print(m)
     
    ret=re.search('(?P<id>d{2})/(?P<name>w{3})','23/com')
    print(ret.group())#23/com
    print(ret.group('id'))#23
    
    
    ret=re.search('(ab)|d','rabhdg8sd')
    print(ret.group())#ab
    
    
    import re
    #1
    re.findall('a','alvin yuan')    #返回所有满足匹配条件的结果,放在列表里
    #2
    re.search('a','alvin yuan').group()  #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
                                         # 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
     
    #3
    re.match('a','abc').group()     #同search,不过尽在字符串开始处进行匹配
     
    #4
    ret=re.split('[ab]','abcd')     #先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
    print(ret)#['', '', 'cd']
     
    #5
    ret=re.sub('d','abc','alvin5yuan6',1)
    print(ret)#alvinabcyuan6
    ret=re.subn('d','abc','alvin5yuan6')
    print(ret)#('alvinabcyuanabc', 2)
     
    #6
    obj=re.compile('d{3}')
    ret=obj.search('abc123eeee')
    print(ret.group())#123
    
    #7
    ret=re.finditer('d','ds3sy4784a')
    print(ret)        #<callable_iterator object at 0x10195f940>
     
    print(next(ret).group())
    print(next(ret).group())

    优先级:  ()分组的作用就是优先匹配

    import re
     
    ret=re.findall('www.(baidu|oldboy).com','www.oldboy.com')
    print(ret)#['oldboy']     这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可
     
    ret=re.findall('www.(?:baidu|oldboy).com','www.oldboy.com')
    print(ret)#['www.oldboy.com']

    二:configparser模块  文件配置,是按照字典模式写入

    写入:

    import configparser
    
    config = configparser.ConfigParser()
    config['DEFAULT'] = {'ServerAliverInterval': '45',
                          'Compression': 'yes',
                           'CompressionLevel':'9' }
    config['bitbucket.org'] = {'User':'hg'}
    
    config['topsecret.server.com]'] = {'Port':'50022',
                                       'ForwardX11':'no'}
    with open('example.ini','w') as configfile:
        config.write(configfile)
    
    
    
    
    #config
    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    编辑:增删改查:

    import configparser
    
    config = configparser.ConfigParser()
    
    #---------------------------------------------查
    print(config.sections())   #[]
    
    config.read('example.ini')
    
    print(config.sections())   #['bitbucket.org', 'topsecret.server.com']
    
    print('bytebong.com' in config)# False
    
    print(config['bitbucket.org']['User']) # hg
    
    print(config['DEFAULT']['Compression']) #yes
    
    print(config['topsecret.server.com']['ForwardX11'])  #no
    
    
    for key in config['bitbucket.org']:
        print(key)
    
    
    # user
    # serveraliveinterval
    # compression
    # compressionlevel
    # forwardx11
    
    
    print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
    print(config.items('bitbucket.org'))  #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
    
    print(config.get('bitbucket.org','compression'))#yes
    
    
    #---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))
    
    
    config.add_section('yuan')
    
    config.remove_section('topsecret.server.com')
    config.remove_option('bitbucket.org','user')
    
    config.set('bitbucket.org','k1','11111')
    
    config.write(open('i.cfg', "w"))
    View Code

    三:hashlib模块  用于加密相关操作,提供MD5算法

    • 一对字符串可以转换成密文且不能反解
    • 一对字符串只有一个MD5,如果加入其它,则可防止被篡改。
  • 相关阅读:
    [Swift实际操作]七、常见概念-(2)点CGPoint和变形CGAffineTransform的使用
    [Swift实际操作]七、常见概念-(1).范围Range、ClosedRange和NSRange的使用实际操作
    [Swift]LeetCode263. 丑数 | Ugly Number
    [Swift]LeetCode258. 各位相加 | Add Digits
    [Swift]LeetCode920. 播放列表的数量 | Number of Music Playlists
    Web开发中,使用表格来展示每个角色对应的权限
    Web开发中,使用表格来展示每个角色对应的权限
    请妥善保管自己的QQ等网络帐号
    请妥善保管自己的QQ等网络帐号
    网络广告行业资料整理
  • 原文地址:https://www.cnblogs.com/xyd134/p/6508578.html
Copyright © 2020-2023  润新知