zoukankan      html  css  js  c++  java
  • day5

    python 使用模块帮助

    1 import time 
    2  
    3 help(time) # 可以显示出time模块的使用信息

    1、定义:
    模块:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py结尾的python文件(文件名:test.py对应的模块名:test)

    包:用来从逻辑上组织模块,本质就一个目录(必须带有一个__init__.py文件)

    2、导入方法

    import module_name # module_name.方法 , module_name.变量名 使用

    import module_name ,module2_name #可以同时导入多个模块

    from module_alex import * #导入module_alex模块的所有方法及变量 可以直接使用 相当于把模 块里面所有的代码复制过来

    from module_alex import m1,m2 #导入module里面 m1 m2方法或者是变量名

    from module_alex import test1 as test #给导入的包取个别名

    3、import本质(路径搜索和搜索路径)
    导入模块的本质就是把python文件解释一遍

    导入包的本质就是执行该包下的__init__.py文件

    加载一个不在同一级目录的包需要在sys.path 环境变量中把模块的父级目录加进去 当前目录的用 os.path.abspath(__file__) 往上走一层用os.path.dirname( os.path.abspath(__file__) )

    包的导入 1、在__init__.py里面先导入需要用到的模块例:from . import test1

    调用 import testpackage

    testpackage.test1.test()#使用testpackage包下的test1模块下的test方法

    4、导入优化
    from module_name import test

    # import module_name
    #
    # print(module_name.name) #调用模块的变量
    #
    # module_name.test1()  #调用模块的方法
    
    #from module_name import name,test1  # 导入模块的name变量及test1方法
    # from module_name import name as na  # 取个别名
    #
    # print(na)   #可以直接使用
    #
    # test1()
    
    # import testpackage  #导入包  本质是运行包该包里面的init.py文件
    #
    # testpackage.test1.test1()  #使用testpackeage包里面test1模块里面test1方法
    
    import time
    
    help(time)  #查看time帮助信息

    导入包的本质是运行该目录下的__init__.py文件 所以需要在init文件里面先导入该目录下的相应模块 例 from . import test 在当前路径下导入test模块

    time & datetime模块

     1 #_*_coding:utf-8_*_
     2 __author__ = 'Alex Li'
     3 
     4 import time
     5 
     6 
     7 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
     8 # print(time.altzone)  #返回与utc时间的时间差,以秒计算
     9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
    10 # print(time.localtime()) #返回本地时间 的struct time对象格式
    11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
    12 
    13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
    14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
    15 
    16 
    17 
    18 # 日期字符串 转成  时间戳
    19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
    20 # print(string_2_struct)
    21 # #
    22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
    23 # print(struct_2_stamp)
    24 
    25 
    26 
    27 #将时间戳转为字符串格式
    28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
    29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
    30 
    31 
    32 
    33 
    34 
    35 #时间加减
    36 import datetime
    37 
    38 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
    39 #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
    40 # print(datetime.datetime.now() )
    41 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
    42 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
    43 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
    44 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
    45 
    46 
    47 #
    48 # c_time  = datetime.datetime.now()
    49 # print(c_time.replace(minute=3,hour=2)) #时间替换
    DirectiveMeaningNotes
    %a Locale’s abbreviated weekday name.  
    %A Locale’s full weekday name.  
    %b Locale’s abbreviated month name.  
    %B Locale’s full month name.  
    %c Locale’s appropriate date and time representation.  
    %d Day of the month as a decimal number [01,31].  
    %H Hour (24-hour clock) as a decimal number [00,23].  
    %I Hour (12-hour clock) as a decimal number [01,12].  
    %j Day of the year as a decimal number [001,366].  
    %m Month as a decimal number [01,12].  
    %M Minute as a decimal number [00,59].  
    %p Locale’s equivalent of either AM or PM. (1)
    %S Second as a decimal number [00,61]. (2)
    %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
    %w Weekday as a decimal number [0(Sunday),6].  
    %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
    %x Locale’s appropriate date representation.  
    %X Locale’s appropriate time representation.  
    %y Year without century as a decimal number [00,99].  
    %Y Year with century as a decimal number.  
    %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
    %Z Time zone name (no characters if no time zone exists).  
    %% A literal '%' character.

    random模块

    1 mport random
    2 print random.random()
    3 print random.randint(1,2)
    4 print random.randrange(1,10)

    生成随机验证码

    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

    OS模块 

    提供对操作系统进行调用的接口

    os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
    os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
    os.curdir  返回当前目录: ('.')
    os.pardir  获取当前目录的父目录字符串名:('..')
    os.makedirs('dirname1/dirname2')    可生成多层递归目录
    os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
    os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
    os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    os.remove()  删除一个文件
    os.rename("oldname","newname")  重命名文件/目录
    os.stat('path/filename')  获取文件/目录信息
    os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    os.linesep    输出当前平台使用的行终止符,win下为"	
    ",Linux下为"
    "
    os.pathsep    输出用于分割文件路径的字符串
    os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    os.system("bash command")  运行shell命令,直接显示
    os.environ  获取系统环境变量
    os.path.abspath(path)  返回path规范化的绝对路径
    os.path.split(path)  将path分割成目录和文件名二元组返回
    os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
    os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
    os.path.isabs(path)  如果path是绝对路径,返回True
    os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
    os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
    os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
    os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

    sys模块

    sys.argv           命令行参数List,第一个元素是程序本身路径
    sys.exit(n)        退出程序,正常退出时exit(0)
    sys.version        获取Python解释程序的版本信息
    sys.maxint         最大的Int值
    sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform       返回操作系统平台名称
    sys.stdout.write('please:')
    val = sys.stdin.readline()[:-1]

    shutil 模块

    import hashlib
     
    # ######## md5 ########
     
    hash = hashlib.md5('898oaFs09f')
    hash.update('admin')
    print hash.hexdigest()

    还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密

    import hmac
    h = hmac.new('wueiqi')
    h.update('hellowo')
    print h.hexdigest()

    四、json 和 pickle 

    用于序列化的两个模块

    • json,用于字符串 和 python数据类型间进行转换
    • pickle,用于python特有的类型 和 python的数据类型间进行转换

    Json模块提供了四个功能:dumps、dump、loads、load

    pickle模块提供了四个功能:dumps、dump、loads、load

    shelve 模块

    shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

    import shelve
     
    d = shelve.open('shelve_test') #打开一个文件
     
    class Test(object):
        def __init__(self,n):
            self.n = n
     
     
    t = Test(123) 
    t2 = Test(123334)
     
    name = ["alex","rain","test"]
    d["test"] = name #持久化列表
    d["t1"] = t      #持久化类
    d["t2"] = t2
     
    d.close()

    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生成一个这样的文档怎么做呢?

     1 import configparser
     2  
     3 config = configparser.ConfigParser()
     4 config["DEFAULT"] = {'ServerAliveInterval': '45',
     5                       'Compression': 'yes',
     6                      'CompressionLevel': '9'}
     7  
     8 config['bitbucket.org'] = {}
     9 config['bitbucket.org']['User'] = 'hg'
    10 config['topsecret.server.com'] = {}
    11 topsecret = config['topsecret.server.com']
    12 topsecret['Host Port'] = '50022'     # mutates the parser
    13 topsecret['ForwardX11'] = 'no'  # same here
    14 config['DEFAULT']['ForwardX11'] = 'yes'
    15 with open('example.ini', 'w') as configfile:
    16    config.write(configfile)

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

     1 >>> import configparser
     2 >>> config = configparser.ConfigParser()
     3 >>> config.sections()
     4 []
     5 >>> config.read('example.ini')
     6 ['example.ini']
     7 >>> config.sections()
     8 ['bitbucket.org', 'topsecret.server.com']
     9 >>> 'bitbucket.org' in config
    10 True
    11 >>> 'bytebong.com' in config
    12 False
    13 >>> config['bitbucket.org']['User']
    14 'hg'
    15 >>> config['DEFAULT']['Compression']
    16 'yes'
    17 >>> topsecret = config['topsecret.server.com']
    18 >>> topsecret['ForwardX11']
    19 'no'
    20 >>> topsecret['Port']
    21 '50022'
    22 >>> for key in config['bitbucket.org']: print(key)
    23 ...
    24 user
    25 compressionlevel
    26 serveraliveinterval
    27 compression
    28 forwardx11
    29 >>> config['bitbucket.org']['ForwardX11']
    30 'yes'

    configparser增删改查语法

     1 [section1]
     2 k1 = v1
     3 k2:v2
     4   
     5 [section2]
     6 k1 = v1
     7  
     8 import ConfigParser
     9   
    10 config = ConfigParser.ConfigParser()
    11 config.read('i.cfg')
    12   
    13 # ########## 读 ##########
    14 #secs = config.sections()
    15 #print secs
    16 #options = config.options('group2')
    17 #print options
    18   
    19 #item_list = config.items('group2')
    20 #print item_list
    21   
    22 #val = config.get('group1','key')
    23 #val = config.getint('group1','key')
    24   
    25 # ########## 改写 ##########
    26 #sec = config.remove_section('group1')
    27 #config.write(open('i.cfg', "w"))
    28   
    29 #sec = config.has_section('wupeiqi')
    30 #sec = config.add_section('wupeiqi')
    31 #config.write(open('i.cfg', "w"))
    32   
    33   
    34 #config.set('group2','k1',11111)
    35 #config.write(open('i.cfg', "w"))
    36   
    37 #config.remove_option('group2','age')
    38 #config.write(open('i.cfg', "w"))

    re模块 

    常用正则表达式符号

    '.'     默认匹配除
    之外的任意一个字符,若指定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'}

    最常用的匹配语法

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

    仅需轻轻知道的几个匹配模式

    re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)  例 re.search('[a-z]+','adminABC0215',flags=re.I)   忽略大小写

    M(MULTILINE): 多行模式,改变'^''$'的行为(参见上图)
    S(DOTALL): 点任意匹配模式,改变'.'的行为
     
  • 相关阅读:
    Reverse Linked List
    Sqrt(x)
    Convert Sorted Array to Binary Search Tree
    Remove Linked List Elements
    Happy Number
    Length of Last Word
    Pow(x, n)
    Rotate Image
    Permutations
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/qq769080870/p/8523525.html
Copyright © 2011-2022 走看看