• 12-14 模块


    模块:一个py文件成为一个模块
    好处:大大提高了可维护性

    分为三种:
    Python标准库模块 第三方模块 应用程序自定义模块

    import:
    执行了对应文件
    引入变量名
    解释器目录下调用 方式:

    from web.web1.web2.web3.cal import add
    from web.web1.web2.web3 import cal
    
    cal.py: 
    def add
      test.py:
      import cal
      print(cal.add(3,5))
    
    or
    from cal import *    #不推荐 容易出麻烦
    直接add



    模块最后的调试代码前加上
    if __name__=='__main__':
    XXXXX

    内置模块:
    os与操作系统打交道 详见随笔——文件处理

    最重要:logging模块 re模块(正则模块)


    time模块

    import time 
    #时间戳 做计算用
    print(time.time()) #秒数 从1970.1.1凌晨算起 1970 Unix诞生时间
    
    print(time.localtime())    #struct_time
    t=time.localtime()
    print(t.tm_year)
    
    #将结构化时间转换为时间戳
    print(time.mktime(time.localtime()))
    #将结构化时间转换为字符串时间
    print(time.strftime('%Y/%m/%d %X',time.localtime()))
    #将字符串时间转换为结构化时间
    print(wime.strptime('2016:12:24:17:50:36','%Y:%m:%d:%X'))
    #直接看时间
    print(time.asctime())
    print(time.ctime())
    
    import datatime
    print(datatime.datatime.now())    #符合我们习惯的时间


    random模块

    import random
    ret=random.randint(1,3)    #0-1随机浮点数
    ret=random.randrange(1,3)
    ret=random.choice([11,22])
    ret=random.sample([11,22,33,66,99,55],2)
    print(ret)
    
    
    ret=[1,2,3,4,5]
    random.shuffle(ret)
    
    def v_code():
      ret=""
      for i in range (5):
        num=random.randint(0,9)
        alf=chr(random.randint(65,122))
        s=str(random.choice([num,alf]))
        ret+=s
      return ret
    print(ret)



    sys模块
    sys.argv #命令行参数list 第一个元素是程序本身路径
    sys.exit #退出程序 正常退出时exit(0)
    sys.stdout.write('#') #进度条~~~print

    json & pickle #数据交换
    import json

    dic={"name":"alex"}

    data=json.dumps(dic) #将单引号变成双引号 数据类型变为字符串
    print(type(data))

    json.loads() #与上述相反


    import pickle
    dic={'name':'alvin','age':23,'sex':'male'}
    j=pickle.dumps(dic) #处理为字节bytes
    pickle写入文件 人类不可读 识别数据类型更多

    shelve模块:只有一个open 不常用 了解

    XML模块

    import xml.etree.ElementTree as ET
    
    tree = ET.parse("xml_lesson")
    root = tree.getroot()
    print(root.tag)
    
    for i in root:
      # print(i.tag) #标签
      print(i.attrib) #属性
      for j in i:
        print(j.tag)
        print(j.text) #所有标签文本内容
    
    #只遍历year标签
    for node in root.iter('year'):
      print(node.tag,node.text)
    
    #修改
    for node in root.iter('year')
      new_year=int(node.text)+1
      node.text=str(new_year)
      node.set("updated","yes")
    
    tree.write("xmltest.xml")
    
    #删除
    for country in root.findall('country')
      rank=int(country.find('rank').text)
      if rank>50:
        root.remove(country)
    
    #创建xml文件
    import xml.etree.ElementTree as ET
    new_xml=ET.Element('namelist')
    
    name = ET.SubElement(new_xml,'name',attrib={"enrolled":"yes"})
    age=ET.SubElement(name,"age",attrib={"checked":"no"})
    sex=ET.SubElement(name,"sex")
    sex.text='33'
    #name2=
    
    et=ET.ElementTree(new_xml) #生成文档对象
    et,write("test.xml,encoding="utf-8",xml_declaration=True)
    
    #ET.dump(new_xml) #打印生成的格式

     

    re模块 正则

    match和group

     1 #match用法
     2 #group用法
     3 import re
     4 content = 'Hello 1234567 78954 World_This is a Regex Demo'
     5 print(len(content))
     6 result = re.match('^Hellos(d+)s(d+)sWorld',content)
     7 print(result)
     8 print(result.group())
     9 print(result.group(2))
    10 print(result.span())
    View Code

    贪婪匹配与非贪婪匹配

    import re
    # content = 'Hello 123 4567 World_This is a Regex Demo'
    # # 贪婪匹配
    # result = re.match('^He.*(d+).*Demo$',content)
    # print(result.group(1))
    # #非贪婪匹配
    # result = re.match('^He.*?(d+).*Demo$',content)
    # print(result.group(1))
    
    #但是如果在结尾非贪婪匹配,就可能啥都没了
    content1 = 'http://weibo.com/comment/kEraCN'
    result1 = re.match('http.*?comment/(.*?)',content1)
    result2 = re.match('http.*?comment/(.*)',content1)
    print(result1.group(1))
    print(result2.group(1))
    View Code

    注意修饰符号re.S和转义字符

    import re
    # content = '''Hellp 1234567 World_this
    # is a Regex Demo
    # '''
    # result = re.match('^He.*?(d+).*?Demo$',content,re.S)   #最后的东西作用在于使之可以匹配到换行符
    # print(result)
    
    #转义匹配
    content1 = '(百度)www.baidu.com'
    result = re.match('(百度)www.baidu.com',content1)         #转义字符~~~
    print(result)
    View Code

    search烘托findall

    import re
    content = 'Extra strings Hello 1234567 78954 World_This is a Regex Demo Extra strings'
    # result = re.match('Hello.*?(d+).*?Demo',content)     error:None
    result = re.search('Hello.*?(d+).*?Demo',content)
    print(result)
    #serach只能找到一个 全部找到依靠findall()
    View Code

    a = 'akjghkhdkgalexkjgkh
    re.findall('alex',a)

    元字符 . ^ $ * + ? {} [] | ()
    re.findall('a..x','akjghkhdkgalexkjgkh') # .通配符

    # ^ 以XX开头 ^必须放最前头
    re.findall('^a..x',‘aghdgjgsgsgjks’)

    # $ 以Xx结尾
    re.findall('a..x$','ksjaghdgsjcxx') #结尾必须是aXXx

    # * + ? {} 重复
    re.findall('a*','ksjaaaaghdgsjcxx') #匹配重复几个a
    re.findall('alex*','ksjaleghdgsjcxx') #* [0,+00]
    re.findall('alex+','ksjalexxxghdgsjcxx')#+ 匹配[1,+00]
    # ? 匹配[0,1] 同上述例子 最多一个x
    # {} 匹配次数自定
    re.findall('alex{0,6}','ksjaleghdgsjcxx')

    #上述均是贪婪匹配 修改为惰性匹配
    # []
    re.findall("x[yz]","xyuuuxzuuu") #二选一
    re.findall("x[a*z]","xyuuuxzuuu") #中括号内 *是普通字符
    re.findall("x[a-z]","xyuuuxzuuu") #q后面a-z的所有字母都可以
    re.findall("x[^a-z]","xyuuuxzuuu") #非a-z的都可以
    re.findall("([^()]*)","21+(6*5+5*(2+3))") #取最内层括号

    # | 管道符 或者

    # 重要性max 无意义的有意义 有意义的无意义
    d 匹配任何十进制数
    D 匹配任何非数字字符 相当于0-9
    s 匹配任何空白字符
    S 匹配任何非空白字符
    w 匹配任何字母数字
    W 匹配任何非字母数字
     匹配一个特殊字符边界 比如空格 & # 等

    re.findall("I\b","hello I am List")#
    re.findall(r"I","hello I am List")

    re.findall("(?P<name>[a-z]+)","jdzhgadgsgf365j")
    re.search("(?P<name>[a-z]+)(?P<age>d+)","jdzhgadgsgf365j").group('name')

    re下方法
    re.match #search下加^ 匹配开头
    re.split
    re.split("[ |]","hello abc def") #以空格或者管道符号分割
    re.split("[ab]","asdabcd")
    ['','sd','','cd']
    re.sub
    re.sub("d+","A","jskafhjf654a6alkjg5546a")
    #把数字变成A
    re.compile("d+")
    com=re.compile("d+") #编译规则赋予com
    调用时候直接com.findall("asmgn54847akjsfh65")

    logging 模块

    import logging
    
    logging.basicConfig(
    level=logging.DEBUG
    filename="logger.log"
    filemode="w"
    format = "%(asctime)s%(lineno)d"
    )
    
    logging.debug('debug message')
    logging.info('info message')
    logging.warning('warning message')
    logging.error('error message')
    logging.critical('critical message')
    
    #-------------------------logger
    #吸星大法~~~!!!
    #同时向屏幕和文件输入
    def logger():
      logger = logging.getLogger()
    
      fm = logging.Formatter("%(asctime)s %(message)s")
    
      fh = logging.FileHandler("test_log") #向文件发送内容
      ch = logging.StreamHandler() #向屏幕发送
    
      logger.addHandler(fh)
      logger.addHandler(ch)
    
      returm logger
    
    logging.debug('debug message')
    logging.info('info message')
    logging.warning('warning message')
    logging.error('error message')
    logging.critical('critical message')





    ,

  • 相关阅读:
    内网安全隐藏通信隧道基础&&网络通信隧道之一ICMP隧道
    windows server2012 r2 .net framework 3.5失败
    awvas启动不起来解决方案
    Kali Linux解压包命令:
    kali linux 中python2不带pip的解决方法
    内网渗透信息收集
    团队作业(二):需求分析
    ORA00600: internal error code, arguments: [16513], [1403] 恢复
    helpyouhelpyou@cock.li 加密数据库恢复
    合成孔径雷达成像——算法与实现内容简要:第1章
  • 原文地址:https://www.cnblogs.com/louzhiyuan/p/10434462.html
Copyright © 2020-2023  润新知