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

    一、time

    时间戳(timestamp):time.time()
    延迟线程的运行:time.sleep(secs)
    (指定时间戳下的)当前时区时间:time.localtime([secs])
    (指定时间戳下的)格林威治时间:time.gmtime([secs])
    (指定时间元组下的)格式化时间:time.strftime(fmt[,tupletime])
    
    %y 两位数的年份表示(00-99)
    %Y 四位数的年份表示(000-9999)
    %m 月份(01-12)
    %d 月内中的一天(0-31)
    %H 24小时制小时数(0-23)
    %I 12小时制小时数(01-12)
    %M 分钟数(00=59)
    %S 秒(00-59)
    %a 本地简化星期名称
    %A 本地完整星期名称
    %b 本地简化的月份名称
    %B 本地完整的月份名称
    %c 本地相应的日期表示和时间表示
    %j 年内的一天(001-366)
    %p 本地A.M.或P.M.的等价符
    %U 一年中的星期数(00-53)星期天为星期的开始
    %w 星期(0-6),星期天为星期的开始
    %W 一年中的星期数(00-53)星期一为星期的开始
    %x 本地相应的日期表示
    %X 本地相应的时间表示
    %Z 当前时区的名称
    %% %号本身

    示例:

    print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
    print(time.altzone)  #返回与utc时间的时间差,以秒计算
    print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
    print(time.localtime()) #返回本地时间 的struct time对象格式
    print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
    print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
    
    # 日期字符串 转成  时间戳
    string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
    print(string_2_struct)
    
    struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
    print(struct_2_stamp)
    
    #将时间戳转为字符串格式
     print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式  

    二、calendar

    判断闰年:calendar.isleap(year)
    查看某年某月日历:calendar.month(year, mouth)
    查看某年某月起始星期与当月天数:calendar.monthrange(year, mouth)
    查看某年某月某日是星期几:calendar.weekday(year, month, day)
    # 注:0代表星期一
    

    三、datatime

    当前时间:datetime.datetime.now()
    昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
    修改时间:datatime_obj.replace([...])
    格式化时间戳:datetime.date.fromtimestamp(timestamp)

    示例:

    print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
    print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
    print(datetime.datetime.now() )
    print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
    print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
    print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
    print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
    
    c_time  = datetime.datetime.now()
    print(c_time.replace(minute=3,hour=2)) #时间替换 

    四、sys

    命令行参数List,第一个元素是程序本身路径:sys.argv
    退出程序,正常退出时exit(0):sys.exit(n) 
    获取Python解释程序的版本信息:sys.version
    最大int值:sys.maxsize | sys.maxint
    环境变量:sys.path
    操作系统平台名称:sys.platform
    

    五、os

    生成单级目录:os.mkdir('dirname')
    生成多层目录:os.makedirs('dirname1/.../dirnamen2')
    重命名:os.rename("oldname","newname") 
    工作目录:os.getcwd()
    删除单层空目录:os.rmdir('dirname')
    移除多层空目录:os.removedirs('dirname1/.../dirnamen') 
    列举目录下所有资源:os.listdir('dirname')
    路径分隔符:os.sep
    行终止符:os.linesep
    文件分隔符:os.pathsep
    操作系统名:os.name
    操作系统环境变量:os.environ
    执行shell脚本:os.system() 
    os.path:系统路径操作 ''' 执行文件的当前路径:__file__ 返回path规范化的绝对路径:os.path.abspath(path) 将path分割成目录和文件名二元组返回:os.path.split(path) 上一级目录:os.path.dirname(path) 最后一级名称:os.path.basename(path) 指定路径是否存在:os.path.exists(path) 是否是绝对路径:os.path.isabs(path) 是否是文件:os.path.isfile(path) 是否是路径:os.path.isdir(path) 路径拼接:os.path.join(path1[, path2[, ...]]) 最后存取时间:os.path.getatime(path) 最后修改时间:os.path.getmtime(path) 目标大小:os.path.getsize(path)
    normcase函数
    在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。
    >>> os.path.normcase('c:/windows\system32\')   
    'c:\windows\system32\'   
       
    normpath函数
    规范化路径,如..和/
    >>> os.path.normpath('c://windows\System32\../Temp/')   
    'c:\windows\Temp'   
    
    >>> a='/Users/jieli/test1/\a1/\\aa.py/../..'
    >>> print(os.path.normpath(a))
    /Users/jieli/test1
    

    六、random

    (0, 1):random.random()
    [1, 10]:random.randint(1, 10)
    [1, 10):random.randrange(1, 10)
    (1, 10):random.uniform(1, 10)
    单例集合随机选择1个:random.choice(item)
    单例集合随机选择n个:random.sample(item, n)
    洗牌单列集合:random.shuffle(item)  

    示例:生成随机验证码

    import random
    checkcode = ''
    for i in range(4):
        current = random.randrange(0,4)
        if current != i:
            temp = chr(random.randint(65,90))
        else:
            temp = random.randint(0,9)
        checkcode += str(temp)
    print checkcode

    七、json

    # json: {} 与 [] 嵌套的数据
    # 注:json中的字符串必须全部用""来标识
    
    序列化:对象 => 字符串
    序列化成字符串:json.dumps(json_obj)
    序列化字符串到文件中:json.dump(json_obj, write_file)
    
    # 注:字符形式操作
    反序列化成对象:json.loads(json_str)
    从文件读流中反序列化成对象:json.load(read_file)
    

    八、pickle

    序列化:对象 => 字符串
    序列化成字符串:pickle.dumps(obj)
    序列化字符串到文件中:pickle.dump(obj, write_bytes_file)
    
    # 注:字节形式操作
    反序列化成对象:pickle.loads(bytes_str)
    从文件读流中反序列化成对象:pickle.load(read_bytes_file)
    

    九、shutil(可以操作权限的处理文件模块)

    # 基于路径的文件复制:
    shutil.copyfile('source_file', 'target_file')
    
    # 基于流的文件复制:
    with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
        shutil.copyfileobj(r, w)
        
    # 递归删除目标目录
    shutil.rmtree('target_folder')
    
    # 文件移动
    shutil.remove('old_file', 'new_file')
    
    # 文件夹压缩
    shutil.make_archive('file_name', 'format', 'archive_path')
    
    # 文件夹解压
    shutil.unpack_archive('unpack_file', 'unpack_name', 'format')
    

    十、shevle(可以用字典存取数据到文件的序列化模块)

    # 将序列化文件操作dump与load进行封装
    s_dic = shelve.open("target_file", writeback=True)  # 注:writeback允许序列化的可变类型,可以直接修改值
    # 序列化::存
    s_dic['key1'] = 'value1'
    s_dic['key2'] = 'value2'
    # 反序列化:取
    print(s_dic['key1'])
    # 文件这样的释放
    s_dic.close()
    

    十一、logging

    1) root logging的基本使用:五个级别
    2)root logging的基本配置:logging.basicConfig()
    3)logging模块四个核心:Logger | Filter | Handler | Formater
    4)logging模块的配置与使用
    	-- 配置文件:LOGGING_DIC = {}
    	-- 加载配置文件:logging.config.dictConfig(LOGGING_DIC) => logging.getLogger('log_name')
    

    十二、hashlib模块(加密)

    import hashlib
    # 基本使用
    cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8'))
    print(cipher.hexdigest())  # 加密结果码
    
    # 加盐
    cipher = hashlib.md5()
    cipher.update('前盐'.encode('utf-8'))
    cipher.update('需要加密的数据'.encode('utf-8'))
    cipher.update('后盐'.encode('utf-8'))
    print(cipher.hexdigest())  # 加密结果码
    
    # 其他算法
    cipher = hashlib.sha3_256(b'')
    print(cipher.hexdigest())
    cipher = hashlib.sha3_512(b'')
    print(cipher.hexdigest())  

    十三、hmac模块(加密)

    # 必须加盐
    cipher = hmac.new('盐'.encode('utf-8'))
    cipher.update('数据'.encode('utf-8'))
    print(cipher.hexdigest())
    

    十四、configparser模块(操作配置文件)

    # my.ini
    [section1]
    option1_1 = value1_1
    option1_2 = value1_2
    
    [section2]
    option2_1 = value2_1
    option2_2 = value2_2
    import configparser
    parser = configparser.ConfigParser()
    # 读
    parser.read('my.ini', encoding='utf-8')
    # 所有section
    print(parser.sections())  
    # 某section下所有option
    print(parser.options('section_name'))  
    # 某section下某option对应的值
    print(parser.get('section_name', 'option_name')) 
    
    # 写
    parser.set('section_name', 'option_name', 'value')
    parser.write(open('my.ini', 'w'))
    

    十五、subprocess模块(操作shell命令)

    import subprocess
    order = subprocess.Popen('终端命令', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    suc_res = order.stdout.read().decode('系统默认编码')
    err_res = order.stderr.read().decode('系统默认编码')
    
    order = subprocess.run('终端命令', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    suc_res = order.stdout.decode('系统默认编码')
    err_res = order.stderr.decode('系统默认编码')

    常用subprocess方法示例

    #执行命令,返回命令执行状态 , 0 or 非0
    >>> retcode = subprocess.call(["ls", "-l"])
    
    #执行命令,如果命令结果为0,就正常返回,否则抛异常
    >>> subprocess.check_call(["ls", "-l"])
    0
    
    #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果 
    >>> subprocess.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls')
    
    #接收字符串格式命令,并返回结果
    >>> subprocess.getoutput('ls /bin/ls')
    '/bin/ls'
    
    #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
    >>> res=subprocess.check_output(['ls','-l'])
    >>> res
    b'total 0
    drwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM
    ' 

    十六、xlrd模块(excel读)

    			年终报表				
    		教学部	市场部	咨询部	总计
    Jan-19	10		15		5	30
    Feb-19	10		15		5	30
    Mar-19	10		15		5	30
    Apr-19	10		15		5	30
    May-19	10		15		5	30
    Jun-19	10		15		5	30
    Jul-19	10		15		5	30
    Aug-19	10		15		5	30
    Sep-19	10		15		5	30
    Oct-19	10		15		5	30
    Nov-19	10		15		5	30
    Dec-19	10		15		5	30
    import xlrd
    # 读取文件
    work_book = xlrd.open_workbook("机密数据.xlsx")
    # 获取所有所有表格名称
    print(work_book.sheet_names())
    # 选取一个表
    sheet = work_book.sheet_by_index(1)
    # 表格名称
    print(sheet.name)
    # 行数
    print(sheet.nrows)
    # 列数
    print(sheet.ncols)
    # 某行全部
    print(sheet.row(6))
    # 某列全部
    print(sheet.col(6))
    # 某行列区间
    print(sheet.row_slice(6, start_colx=0, end_colx=4))
    # 某列行区间
    print(sheet.col_slice(3, start_colx=3, end_colx=6))
    # 某行类型 | 值
    print(sheet.row_types(6), sheet.row_values(6))
    # 单元格
    print(sheet.cell(6,0).value) # 取值
    print(sheet.cell(6,0).ctype) # 取类型
    print(sheet.cell_value(6,0)) # 直接取值
    print(sheet.row(6)[0])
    # 时间格式转换
    print(xlrd.xldate_as_datetime(sheet.cell(6, 0).value, 0))
    

    十七、xlwt模块(excel写)

    import xlwt
    # 创建工作簿
    work = xlwt.Workbook()
    # 创建一个表
    sheet = work.add_sheet("员工信息数据")
    # 创建一个字体对象
    font = xlwt.Font()
    font.name = "Times New Roman"  # 字体名称
    font.bold = True  # 加粗
    font.italic = True  # 斜体
    font.underline = True  # 下划线
    # 创建一个样式对象
    style = xlwt.XFStyle()
    style.font = font
    keys = ['Owen', 'Zero', 'Egon', 'Liuxx', 'Yhh']
    # 写入标题
    for k in keys:
        sheet.write(0, keys.index(k), k, style)
    # 写入数据
    sheet.write(1, 0, 'cool', style)
    # 保存至文件
    work.save("test.xls")
    

    十八、xml模块

    <?xml version="1.0"?>
    <data>
        <country name="Liechtenstein">
            <rank updated="yes">2</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country name="Singapore">
            <rank updated="yes">5</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country name="Panama">
            <rank updated="yes">69</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>
    import xml.etree.ElementTree as ET
    # 读文件
    tree = ET.parse("xmltest.xml")
    # 根节点
    root_ele = tree.getroot()
    # 遍历下一级
    for ele in root_ele:
        print(ele)
        
    # 全文搜索指定名的子标签
    ele.iter("标签名")
    # 非全文查找满足条件的第一个子标签
    ele.find("标签名")
    # 非全文查找满足条件的所有子标签
    ele.findall("标签名")
    
    # 标签名
    ele.tag
    # 标签内容
    ele.text
    # 标签属性
    ele.attrib
    
    # 修改
    ele.tag = "新标签名"
    ele.text = "新文本"
    ele.set("属性名", "新属性值")
    
    # 删除
    sup_ele.remove(sub_ele)
    
    # 添加
    my_ele=ET.Element('myEle')
    my_ele.text = 'new_ele' 
    my_ele.attrib = {'name': 'my_ele'}
    root.append(my_ele)
    
    # 重新写入硬盘
    tree.write("xmltest.xml") 

    十九、re

    python中re模块提供了正则表达式相关操作

    字符:

    . 匹配除换行符以外的任意字符
    w	匹配字母或数字或下划线或汉字
    s	匹配任意的空白符
    d	匹配数字
    	匹配单词的开始或结束
    ^	匹配字符串的开始
    $	匹配字符串的结束
    

    次数:

    * 重复零次或更多次
    +	重复一次或更多次
    ?	重复零次或一次
    {n}	重复n次
    {n,}	重复n次或更多次
    {n,m}	重复n到m次
    

    match

    # match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
     
     
     match(pattern, string, flags=0)
     # pattern: 正则模型
     # string : 要匹配的字符串
     # falgs  : 匹配模式
         X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
         I  IGNORECASE  Perform case-insensitive matching.
         M  MULTILINE   "^" matches the beginning of lines (after a newline)
                        as well as the string.
                        "$" matches the end of lines (before a newline) as well
                        as the end of the string.
         S  DOTALL      "." matches any character at all, including the newline.
     
         A  ASCII       For string patterns, make w, W, , B, d, D
                        match the corresponding ASCII character categories
                        (rather than the whole Unicode categories, which is the
                        default).
                        For bytes patterns, this flag is the only available
                        behaviour and needn't be specified.
          
         L  LOCALE      Make w, W, , B, dependent on the current locale.
         U  UNICODE     For compatibility only. Ignored for string patterns (it
                        is the default), and forbidden for bytes patterns.  

    示例:

      # 无分组
            r = re.match("hw+", origin)
            print(r.group())     # 获取匹配到的所有结果
            print(r.groups())    # 获取模型中匹配到的分组结果
            print(r.groupdict()) # 获取模型中匹配到的分组结果
    
            # 有分组
    
            # 为何要有分组?提取匹配成功的指定内容(先匹配成功全部正则,再匹配成功的局部内容提取出来)
    
            r = re.match("h(w+).*(?P<name>d)$", origin)
            print(r.group())     # 获取匹配到的所有结果
            print(r.groups())    # 获取模型中匹配到的分组结果
            print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
    

    search  

    # search,浏览整个字符串去匹配第一个,未匹配成功返回None
    # search(pattern, string, flags=0)  

    示例:

            # 无分组
    
            r = re.search("aw+", origin)
            print(r.group())     # 获取匹配到的所有结果
            print(r.groups())    # 获取模型中匹配到的分组结果
            print(r.groupdict()) # 获取模型中匹配到的分组结果
    
            # 有分组
    
            r = re.search("a(w+).*(?P<name>d)$", origin)
            print(r.group())     # 获取匹配到的所有结果
            print(r.groups())    # 获取模型中匹配到的分组结果
            print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
    

    findall

    # findall,获取非重复的匹配列表;如果有一个组则以列表形式返回,且每一个匹配均是字符串;如果模型中有多个组,则以列表形式返回,且每一个匹配均是元祖;
    # 空的匹配也会包含在结果中
    #findall(pattern, string, flags=0)    

    示例:

            # 无分组
            r = re.findall("aw+",origin)
            print(r)
    
            # 有分组
            origin = "hello alex bcd abcd lge acd 19"
            r = re.findall("a((w*)c)(d)", origin)
            print(r)
    

    sub

    # sub,替换匹配成功的指定位置字符串
     
    sub(pattern, repl, string, count=0, flags=0)
    # pattern: 正则模型
    # repl   : 要替换的字符串或可执行对象
    # string : 要匹配的字符串
    # count  : 指定匹配个数
    # flags  : 匹配模式  

    示例:

      # 与分组无关
    
            origin = "hello alex bcd alex lge alex acd 19"
            r = re.sub("aw+", "999", origin, 2)
            print(r)
    

    split

    # split,根据正则匹配分割字符串
     
    split(pattern, string, maxsplit=0, flags=0)
    # pattern: 正则模型
    # string : 要匹配的字符串
    # maxsplit:指定分割个数
    # flags  : 匹配模式 

    示例:

            # 无分组
            origin = "hello alex bcd alex lge alex acd 19"
            r = re.split("alex", origin, 1)
            print(r)
    
            # 有分组
            
            origin = "hello alex bcd alex lge alex acd 19"
            r1 = re.split("(alex)", origin, 1)
            print(r1)
            r2 = re.split("(al(ex))", origin, 1)
            print(r2)  

    常用正则表达式

    IP:
    ^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$
    手机号:
    ^1[3|4|5|8][0-9]d{8}$
    邮箱:
    [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+

    参考文档:

    https://www.cnblogs.com/alex3714/articles/5161349.html    

    http://www.cnblogs.com/wupeiqi/articles/5501365.html                                                                            

  • 相关阅读:
    【学习笔记/题解】树上启发式合并/CF600E Lomsat gelral
    【学习笔记/题解】虚树/[SDOI2011]消耗战
    【题解】 [GZOI2017]小z玩游戏
    【题解】CF1426E Rock, Paper, Scissors
    【题解】CF1426D Non-zero Segments
    【题解】NOIP2018 填数游戏
    【题解】NOIP2018 旅行
    【题解】NOIP2018 赛道修建
    【题解】时间复杂度
    【题解】「MCOI-02」Convex Hull 凸包
  • 原文地址:https://www.cnblogs.com/panwenbin-logs/p/10803554.html
Copyright © 2011-2022 走看看