zoukankan      html  css  js  c++  java
  • 常用模块

    1.
    什么是序列化
      序列化就是将内存中的数据类型转成另外一种格式

    即:
      字典 - --------序列化 - -------->其他的格式 - -------------->存到硬盘
      硬盘 - --读取 - --->其他格式 - ---------反序列化 - ------->字典

    2.
    为什么要序列化
      1、持久保存程序的运行状态
      2、数据的跨平台交互

    3.
    如何序列化
    json:(json格式不能识别单引号)
      优点: 这种格式是一种通用的格式, 所有编程语言都能识别
      缺点: 不能识别所有python类型
    pickle
      优点: 能识别所有python类型
      缺点: 只能被python这门编程语言识别

    json序列化与写入文件分开(dumps、loads)
    import json
    
    序列化
    dic = {'a':True,"b":False,'c':'你好’}
    dic_js = json.dumps(dic)
    print(dic_js)
    持久化(写入文件)
    with open('at','wt',encoding='utf-8')as f:
        f.write(dic_js)
    
    
    从文件中读取json格式的字符
    with open('at','rt',encoding='utf-8')as f:
        dic_js = f.read()
        print(dic_js)
    反序列化
    dic = json.loads(dic_js)
    print(dic)
    View Code

     json序列化+持久化(dump、load)

    import json
    dic = {'a':True,"b":False,'c':'你好'}
    序列化
    with open('at','wt',encoding='utf-8')as f:
        json.dump(dic,f)
    
    
    反序列化
    with open('at','rt',encoding='utf-8')as f:
        json.load()
    View Code

    pickle(用法与json相同,注意,读取文件用wb,rb模式)

    序列化、持久化分开
    import pickle
    dic = {'a':True,"b":False,'c':'你好'}
    dic_pic = pickle.dumps(dic)
    with open('at','wb')as f:
        f.write(dic_pic)
    
    with open('at','rb')as f:
        dic_pic = f.read()
        dic=pickle.loads(dic_pic)
    
    
    序列化、持久化连用
    import pickle
    dic = {'a':True,"b":False,'c':'你好'}
    with open('at','wb')as f:
        pickle.dump(dic,f)
    
    with open('at','rb')as f:
        dic = pickle.load(f)
        print(dic)
    View Code

    时间模块time与datetime
    time
    1. 时间戳:time.time()
    应用: 用来计算时间间隔

    2. 格式化的字符串形式: time.strftime('%Y-%m-%d %H:%M:%S')
    应用: 方便地取出格式化字符串形式的时间,用来显示

    3. 结构化的时间: time.localtime()
                time.gmtime()
    应用:
    1.单独获取当前时间的任意部分
    2.用来时间戳与格式化字符串时间之间的转换

    年-月-日 时:分:秒
    t=time.localtime()
    print('%s-%s-%s %s:%s:%s' %(t.tm_year,t.tm_mon,...))

    datetime模块 vs time模块:
         1.获取当前时间更方便
          datetime.datetime.now()
    2. 日期计算更为方便
    datetime.datetime.now()+datetime.timedelta(days=3,hours=2)
    3. 将时间戳转化为常用时间格式
    datetime.datetime.fromtimestamp(123123123)


    random模块(随机模块)
    import random

    print(random.random()) # (0,1)----float 大于0且小于1之间的小数

    print(random.randint(1, 3)) # [1,3] 大于等于1且小于等于3之间的整数

    print(random.randrange(1, 3)) # [1,3) 大于等于1且小于3之间的整数

    print(random.choice([1, '23', [4, 5]])) # 1或者23或者[4,5]

    print(random.sample([1, '23', [4, 5]], 2)) # 列表元素任意2个组合

    print(random.uniform(1, 3)) # 大于1小于3的小数,如1.927109612082716

    item = [1, 3, 5, 7, 9]
    random.shuffle(item) # 打乱item的顺序,相当于"洗牌"
    print(item)

    随机验证码基础版(chr 是把数字按照ASCII表转成字符)
    import random
    res = ""
    for i in range(4):
        num = str(random.randint(0,9))
        max_alp = chr(random.randint(65,90))
        min_alp = chr(random.randint(97,122))
        res += random.choice([num,max_alp,min_alp])
    print(res)
    View Code

    随机验证码函数版
    import random
    def make_code(max_size = 4):
        res = ""
        for i in range(max_size):
            num = str(random.randint(0,9))
            max_alp = chr(random.randint(65,90))
            min_alp = chr(random.randint(97,122))
            res += random.choice([num,max_alp,min_alp])
        return res
    print(make_code(6))
    View Code
    subprocess模块
      sub子
      process进程
      当一个正在运行的应用程序A,开启了另一个应用B,那么B就称为A的子进程








    re模块(正则表达式)
     1
    、什么是正则 
        正则就是用一些特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法 
        或者说:正则就是用来描述一类事物的规则
        
     2、有什么用
        用来处理字符串
     
            1.获取符合规则的字符串内容
           2.判断一个字符串是否符合某个规则

             附加:字符串切割 截取

        3、使用场景
        1.对用户输入的数据进行判断
        2.爬虫从页面文档提取需要的数据

    import re
    #
    # # 要处理的字符串内容
    # text = "123abcA_1s2-33333933"
    # # re正则表达式(规则)
    # reg = "[a-z]"
    
    
    #量词 用于指定前面的表达式重复次数
    # {a,b} 最少a 最多b
    # {,b} 最少0 最多b
    # {a,} 最少a 最多无穷
    # + == {1,}
    # * == 任意次数{,}
    # ? == {0,1}
    
    # 范围匹配
    # |   a|b
    # [abcdefg]  括号中任意一个字符都能匹配
    
    
    
    # res = re.findall(reg,text)
    # print(res)
    
    # 分组  会优先获取分组中内容
    text = '<a href="https://www.baidu.com"/><img src="https://www.baidu.com/xx.jpg"></img>'
    
    reg = '<img src="(.*)"'
    
    print(re.findall(reg,text))
    
    
    # 非获取(捕获)分组
    # 当我们需要把两个表达式当做成体时 可以加括号 但是又不想获取分组中的内容仅仅是为了分组
    # 加上?:
    text = "13221999093"
    # 判断手机号是否是189或132
    print(re.findall("(?:132|189)d{8}",text))
    
    
    # 反向引用
    #不许出现重复三次以上的字符 长度至少6位
    
    pwd = input("请输入密码:")
    # 可以使用分组的序号来拿到前面分组内容
    
    if re.findall(r"(.)11",pwd) :
    
        print("密码格式错误  不允许出现三次重复的字符")
    elif len(pwd) >= 6 and len(pwd) <= 9:
        print("密码格式正确!")
    else:
        print("长度必须为6-9位")
    一些使用方法
    # =================================匹配模式=================================
    #一对一的匹配
    # 'hello'.replace(old,new)
    # 'hello'.find('pattern')
    
    #正则匹配
    import re
    #w与W
    print(re.findall('w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
    print(re.findall('W','hello egon 123')) #[' ', ' ']
    
    #s与S
    print(re.findall('s','hello  egon  123')) #[' ', ' ', ' ', ' ']
    print(re.findall('S','hello  egon  123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
    
    #
     	都是空,都可以被s匹配
    print(re.findall('s','hello 
     egon 	 123')) #[' ', '
    ', ' ', ' ', '	', ' ']
    
    #
    print(re.findall(r'
    ','hello egon 
    123')) #['
    ']
    print(re.findall(r'	','hello egon	123')) #['
    ']
    
    #d与D
    print(re.findall('d','hello egon 123')) #['1', '2', '3']
    print(re.findall('D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
    
    #A与
    print(re.findall('Ahe','hello egon 123')) #['he'],A==>^
    print(re.findall('123','hello egon 123')) #['he'],==>$
    
    #^与$
    print(re.findall('^h','hello egon 123')) #['h']
    print(re.findall('3$','hello egon 123')) #['3']
    
    # 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
    #.
    print(re.findall('a.b','a1b')) #['a1b']
    print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
    print(re.findall('a.b','a
    b')) #[]
    print(re.findall('a.b','a
    b',re.S)) #['a
    b']
    print(re.findall('a.b','a
    b',re.DOTALL)) #['a
    b']同上一条意思一样
    
    #*
    print(re.findall('ab*','bbbbbbb')) #[]
    print(re.findall('ab*','a')) #['a']
    print(re.findall('ab*','abbbb')) #['abbbb']
    
    #?
    print(re.findall('ab?','a')) #['a']
    print(re.findall('ab?','abbb')) #['ab']
    #匹配所有包含小数在内的数字
    print(re.findall('d+.?d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']
    
    #.*默认为贪婪匹配
    print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
    
    #.*?为非贪婪匹配:推荐使用
    print(re.findall('a.*?b','a1b22222222b')) #['a1b']
    
    #+
    print(re.findall('ab+','a')) #[]
    print(re.findall('ab+','abbb')) #['abbb']
    
    #{n,m}
    print(re.findall('ab{2}','abbb')) #['abb']
    print(re.findall('ab{2,4}','abbb')) #['abb']
    print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
    print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'
    
    #[]
    print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
    print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
    print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
    print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
    print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']
    
    ## print(re.findall('a\c','ac')) #对于正则来说a\c确实可以匹配到ac,但是在python解释器读取a\c时,会发生转义,然后交给re去执行,所以抛出异常
    print(re.findall(r'a\c','ac')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
    print(re.findall('a\\c','ac')) #同上面的意思一样,和上面的结果一样都是['a\c']
    
    #():分组
    print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
    print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
    print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
    print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
    print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"']
    
    #|
    print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
    
    
    # ===========================re模块提供的方法介绍===========================
    import re
    #1
    print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
    #2
    print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
    
    #3
    print(re.match('e','alex make love'))    #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
    
    #4
    print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
    
    #5
    print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有
    print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
    print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
    print('===>',re.sub('^(w+)(.*?s)(w+)(.*?s)(w+)(.*?)$',r'52341','alex make love')) #===> love make alex
    
    print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数
    
    
    #6
    obj=re.compile('d{2}')
    
    print(obj.search('abc123eeee').group()) #12
    print(obj.findall('abc123eeee')) #['12'],重用了obj















    logging模块
    import logging

    # 1. 控制日志级别
    # 2. 控制日志格式
    # 3. 控制输出的目标为文件
                 
    logging.basicConfig(filename='access.log', #filename记录文件的路径
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', # 日志的格式
    datefmt='%Y-%m-%d %H:%M:%S %p',        #修改日志格式当中的时间格式                         
    level=10,                     #等级
    )  

     这里需要注意的是不写filename的话,默认是stream=True,后者是输出打印到终端,filename是输出到制定路径,两者不能同时存在
    
    


    logging.debug('debug日志') # 10
    logging.info('info日志') # 20
    logging.warning('warning日志') #30
    logging.error('error日志')#40
    logging.critical('critical日志') #50



    # 1. 能够同时往终端与文件中记录日志
    # 2. 能够修改字符串编码

    import logging

    # 1. logger对象: 负责生产各种级别的日志
    logger1 = logging.getLogger('用户交易') # 日志名用来标识日志的与什么业务有关

    # 2. filter对象: 过滤日志

    # 3. handler对象: 控制日志输出目标位置
    fh1 = logging.FileHandler('a1.log',encoding='utf-8')
    fh2 = logging.FileHandler('a2.log',encoding='utf-8')
    ch = logging.StreamHandler()

    # 4. formmater对象:控制日志格式
    formatter1 = logging.Formatter(
    fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p'
    )

    formatter2 = logging.Formatter(
    fmt='%(asctime)s - %(levelname)s : %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p'
    )

    # 5. 绑定logger对象与handler对象
    logger1.addHandler(fh1)
    logger1.addHandler(fh2)
    logger1.addHandler(ch)

    # 6. 绑定handler对象与formatter对象

    fh1.setFormatter(formatter1)
    fh2.setFormatter(formatter1)
    ch.setFormatter(formatter2)

    # 7. 设置日志级别,有logger对象与handler对象两层关卡,必须都放行最终日志才会放行,通常二者级别相同
    logger1.setLevel(10)
    fh1.setLevel(10)
    fh2.setLevel(10)
    ch.setLevel(10)

    # 8. 使用logger对象产生日志
    logger1.info('alex给egon转账1个亿')







  • 相关阅读:
    Spring学习总结[1]-入门
    MyBatis学习总结[5]-动态 SQL
    MyBatis学习总结[4]-ResultMap子元素
    MyBatis学习总结[3]-多表查询
    MyBatis学习总结[2]-接口式调用
    MyBatis学习总结[1]-入门
    Bootstrap table两种分页示例
    spring ioc原理(看完后大家可以自己写一个spring)
    Junit4单元测试
    数字转换为字母有多少种方式
  • 原文地址:https://www.cnblogs.com/pdun/p/10311436.html
Copyright © 2011-2022 走看看