zoukankan      html  css  js  c++  java
  • W5_import_time_random_os_sys_shelve_xml_configparser_hashlib_hmac_re

    W5_import_time_random_os_sys_shelve_xml_configparser_hashlib_hmac_re

    68.第03章节-Python3.5-模块定义、导入、优化详解1

    1.导入方法:
    import moduel_name
    import moduel1_name ,moduel2_name
    from moduel_name import *
    from moduel_name import m1,m2,m3
    from module_name import m1 as m1_new_name

    2.import本质(路径搜索和搜索路径)
    a).导入模块的本质是把模块python文件解释一遍
    b).导入包的本质:就是执行该包下的__init__.py文件

    import sys,os
    print(sys.path)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(BASE_DIR)
    #或者使用抛入,让BASE_DIR排到最前面
    #sys.path.insert(BASE_DIR)
    print(sys.path)
    

    返回顶部

    69.第04章节-Python3.5-模块定义、导入、优化详解2

    1.导入优化
    from module_name import m1
    可以避免多次调用模块的某一个功能时:重复检索module_name,重复执行module_name

    返回顶部

    70.第05章节-Python3.5-内置模块详解之time与datetime模块

    时间格式分类:

    1,格式化字符
    2.时间戳
    3.结构化数组

    print(help(time))
    time.gmtime() #转为struct_time(tumple) ,结果为UTC时区时间
    time.localtime() #转为struct_time(tumple) ,结果为本地时区时间

    #将时间戳转为字符串格式
    # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
    # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
    

      

    时间转换

    time.mktime
    time.strftime("format_string",struct_tuple)
    time.strptime("time","format_string")
    time.asctime
    time.ctime
    referer:http://blog.51cto.com/egon09/1840425

    时间加减

    import datetime
    
    # 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)) #时间替换
    

    返回顶部

    71.第06章节-Python3.5-内置模块详解之random模块

    random.random()
    random.randint(1,3) #包括3
    random.randrange(1,3) #不包括3
    random.choice("string")
    random.choice([1,2,3])
    items = [1,2,3,4]
    random.shuffle(items)

    随机验证码

    import random
    list_str = []
    for i in range(26):
        list_str.append(chr(i+ord('a')))
    for i in range(10):
        list_str.append(str(i))
    
    print("".join(list_str))
    print(random.sample("".join(list_str),4))
    print(random.sample("abcdefghijklmnopqrstuvwxyz012345678901234567890123456789",4))
    

    返回顶部

    72.第07章节-Python3.5-内置模块详解之OS模块

    os.getcwd()
    os.chdir(r"/to/path") #r'是防止字符转义的
    os.curdir
    os.pardir
    os.makedirs(r'/to/path/a/b/c/d') #递归创建目录
    os.removedirs(r'/to/path/a/b/c/d') #递归删除空目录
    os.mkdir(r'/path') #创意单级目录
    os.rmdir(r'/path') #删除单级空目录
    os.listdir(r'/to/path')
    os.rename("old_name","new_name") #重命名文件或目录
    os.stat()
    os.sep #操作系统的路径分隔符
    os.linesep
    os.pathsep #环境变量中当需要多个路径时,各路径的分隔符
    os.name
    os.system(cmd) #执行命令,返回0或1
    os.environ #获取系统环境变量
    os.path.abspath
    os.path.split(r'/path/file') #文件名与路径分割,二元组返回
    os.path.isfile()
    os.path.isdir()
    os.path.exists()
    os.path.basename()
    os.path.join()
    os.path.getatime()
    os.path.getmtime()
    os.stat("filename") #查看文件权限,各种时间等状态信息
    返回顶部

    73.第08章节-Python3.5-内置模块详解之Sys模块

    sys

    sys.argv
    sys.exit(n)
    sys.version
    sys.maxint
    sys.path #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform 返回操作系统平台名称
    sys.stdout.write("please:")
    val = sys.stdin.readline()[:-1]

    shutil

    
    import shutil
    f1 = open("file_1.txt",encoding="utf-8")
    f2 = open("file_2.txt","w",encoding="utf-8")
    shutil.copyfileobj(f1,f2)
    
    
    shutil.copyfile("file_a.txt","file_b.txt")
    #复制文件内容
    
    shutil.copymode(f_src,f_dst)
    #仅拷贝权限
    
    shutil.copy(f_src,f_dst)  #拷贝权限,文件
    shutil.copy2(f_src,f_dst)  #拷贝文件,状态信息
    shutil.copytree(src,dst,symlinks=False,ignore=None)
    #递归的拷贝文件
    
    shutil.rmtree(path) #递归删除文件
    shutil.move(src,dst) #递归的移动文件
    shutil.make_archive(base_name,format,path)
    #创建压缩包,并返回文件路径
    
    #zipfile压缩
    import zipfile
    z = zipfile.Zipfile("test.zip","w")
    z.write("test_file")
    z.close()
    
    #解压
    z = zipfile.Zipfile("test.zip","r")
    z.extractall()
    z.close()
    
    
    #tarfile压缩
    import tarfile
    

    返回顶部

    74.第09章节-Python3.5-内置模块详解之Shelve模块

    持久化

    import shelve
    import datetime
    name = {
      "name":"alex",
      "age":22
    }
    info = ["job","it","test"]
    time_value = datetime.datetime.now()
    
    f = shelve.open("test.txt")
    f["name"] = name #持久化字典
    f["info"] = info  #持久化列表
    f["time"] = time_value  #持久化datetime
    f.close()
    

    重新加载回来

    import shelve
    f = shelve.open("test.txt")
    
    print(f.get("name"))
    print(f.get("info"))
    print(f.get("time"))
    f.close()
    
    

    返回顶部

    75.76.第10章节-Python3.5-内置模块详解之Xml模块

    返回顶部

    77.第12章节-Python3.5-内置模块详解之Configparser模块

    于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

    来看一个好多软件的常见文档格式如下

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
    
    [bitbucket.org]
    User = hg
    
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no
    
    

    如果想用python生成一个这样的文档怎么做呢?

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

    写完了还可以再读出来哈。

    >>> import configparser
    >>> config = configparser.ConfigParser()
    >>> config.sections()
    []
    >>> config.read('example.ini')
    ['example.ini']
    >>> config.sections()
    ['bitbucket.org', 'topsecret.server.com']
    >>> 'bitbucket.org' in config
    True
    >>> 'bytebong.com' in config
    False
    >>> config['bitbucket.org']['User']
    'hg'
    >>> config['DEFAULT']['Compression']
    'yes'
    >>> topsecret = config['topsecret.server.com']
    >>> topsecret['ForwardX11']
    'no'
    >>> topsecret['Port']
    '50022'
    >>> for key in config['bitbucket.org']: print(key)
    ...
    user
    compressionlevel
    serveraliveinterval
    compression
    forwardx11
    >>> config['bitbucket.org']['ForwardX11']
    'yes'
    

    configparser增删改查语法

    [section1]
    k1 = v1
    k2:v2
    
    [section2]
    k1 = v1
    
    import ConfigParser
    
    config = ConfigParser.ConfigParser()
    config.read('i.cfg')
    
    # ########## 读 ##########
    #secs = config.sections()
    #print secs
    #options = config.options('group2')
    #print options
    
    #item_list = config.items('group2')
    #print item_list
    
    #val = config.get('group1','key')
    #val = config.getint('group1','key')
    
    # ########## 改写 ##########
    #sec = config.remove_section('group1')
    #config.write(open('i.cfg', "w"))
    
    #sec = config.has_section('wupeiqi')
    #sec = config.add_section('wupeiqi')
    #config.write(open('i.cfg', "w"))
    
    
    #config.set('group2','k1',11111)
    #config.write(open('i.cfg', "w"))
    
    #config.remove_option('group2','age')
    #config.write(open('i.cfg', "w"))
    

    返回顶部

    78.第13章节-Python3.5-内置模块详解之Hashlib、Hmac模块

    Hashlib

    import hashlib
    
    m = hashlib.md5()
    m.update("test a string".encode(encoding = "utf-8"))
    print(m.digest())     #10进制格式
    print(m.hexdigest())  #16进制格式,较为常用
    m.update("test another string".encode(encoding = "utf-8"))
    print(m.hexdigest())  #16进制格式,较为常用
    
    m2 = hashlib.md5()
    m2.update("test a stringtest another string".encode(encoding = "utf-8"))
    
    print(m2.hexdigest(),"-->m2:")  #16进制格式,较为常用
    
    m3 = hashlib.sha256()
    m3.update("test a stringtest another string".encode(encoding = "utf-8"))
    print(m3.hexdigest())  #16进制格式,较为常用
    
    

    加盐

    m = hashlib.md5('盐',encodeing='utf-8')
    m.update(b"test a string")
    print(m.hedigest())
    
    

    Hmac模块

    import hmac
    h = hmac.new(b"key123","message aadfjakf".encode(encoding="utf-8"))
    print(h.hexdigest())
    
    

    返回顶部

    79.第14章节-Python3.5-正则表达式Re模块使用详解

    最常用的匹配语法

    re.match 从头开始匹配
    re.search 匹配包含,匹配到一个就返回
    re.findall 把所有匹配到的字符放到以列表中的元素返回
    re.splitall 以匹配到的字符当做列表分隔符
    re.sub 匹配字符并替换

    import re
    # re.match((pattern, string, flags=0))
    res1 = re.match("^Chen","ChengYiEer")
    res2 = re.match("^Chen","CahengYiEer")
    res3 = re.match("^Chend+","Chen123gYiEer")
    
    print("res1:",res1)
    print("res1 match value:",res1.group())
    print("res2:",res2)
    print("res3 match value:",res3.group())
    
    

    常用正则表达式符号

    '.'     默认匹配除
    之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
    '^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","
    abc
    eee",flags=re.MULTILINE)
    '$'     匹配字符结尾,或e.search("foo$","bfoo
    sdfsf",flags=re.MULTILINE).group()也可以
    '*'     匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac")  结果为['abb', 'ab', 'a']
    '+'     匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
    '?'     匹配前一个字符1次或0次
    '{m}'   匹配前一个字符m次
    '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
    '|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
    '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
    
    
    'A'    只从字符开头匹配,re.search("Aabc","alexabc") 是匹配不到的
    ''    匹配字符结尾,同$
    'd'    匹配数字0-9
    'D'    匹配非数字
    'w'    匹配[A-Za-z0-9]
    'W'    匹配非[A-Za-z0-9],即特殊字符
    's'     匹配空白字符、	、
    、
     , re.search("s+","ab	c1
    3").group() 结果 '	'
    
    '(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}
    
    

    返回顶部

    W5 practice

    1. 实现加减乘除及拓号优先级解析
    2. 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )等类似公式后,必须自己解析里面的(),+,-,,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致
  • 相关阅读:
    【leetcode】1020. Partition Array Into Three Parts With Equal Sum
    【leetcode】572. Subtree of Another Tree
    【leetcode】123. Best Time to Buy and Sell Stock III
    【leetcode】309. Best Time to Buy and Sell Stock with Cooldown
    【leetcode】714. Best Time to Buy and Sell Stock with Transaction Fee
    【leetcode】467. Unique Substrings in Wraparound String
    【leetcode】823. Binary Trees With Factors
    【leetcode】143. Reorder List
    【leetcode】1014. Capacity To Ship Packages Within D Days
    【leetcode】1013. Pairs of Songs With Total Durations Divisible by 60
  • 原文地址:https://www.cnblogs.com/rootid/p/9440477.html
Copyright © 2011-2022 走看看