zoukankan      html  css  js  c++  java
  • python学习笔记(六):常用模块

    一、模块、包

    什么是模块?

    模块实质上就是一个python文件,它是用来组织代码的,意思就是说把python代码写到里面,文件名就是模块的名称,test.py test就是模块名称。

    什么是包?

    包,package本质就是一个文件夹,和文件夹不一样的是它有一个__init__.py文件,包是从逻辑上来组织模块的,也就是说它是用来存放模块的,如果你想导入其他目录下的模块,那么这个目录必须是一个包才可以导入。

    导入模块

    import module #导入模块
    from module import *  #导入该模块中的所有方法,慎用
    from module import fun as xx_fun #导入指定的方法,然后起别名
    from module import fun1,fun2,fun3 #导入模块下的多个方法
    #import module,实际上就是把该模块的代码赋值给模块名,也就是module.py里面所有的代码,赋值给了module这个变量,如果是from module import fun,就是把module打开,把module里面的fun方法拿过来使用

    导入模块的本质,就是把python文件拿过来执行一次。

    使用包中的模块需要在__init__.py文件中from . import xxx

    模块分类:

    标准库:python内置的
    开源模块:第三方
    自定义模块:自己写的

    二、os、sys模块

    os:    import os

    print(os.getcwd())#取当前工作目录
        os.chmod("/usr/local",7)#给文件/目录加权限
        print(os.chdir("../"))#更改当前目录
        print(os.curdir)#当前目录
        print(os.pardir)#父目录
        print(os.makedirs("/usr/hehe/hehe1"))#递归创建文件夹,父目录不存在时创建父目录
        print(os.removedirs("/usr/hehe/hehe1"))#递归删除空目录
        print(os.mkdir("test1"))#创建文件夹
        print(os.rmdir("test1"))#删除指定的文件夹
        print(os.remove("test"))#删除文件
        print(os.listdir('.'))#列出一个目录下的所有文件
        os.rename("test","test1")#重命名
    os.system('cd ..')#输入终端命令 print(os.stat("len_os.py"))#获取文件信息 print(os.sep)#当前操作系统的路径分隔符 print(os.linesep)#当前操作系统的换行符 print(os.pathsep)#当前系统的环境变量中每个路径的分隔符,linux是:,windows是; print(os.environ)#当前系统的环境变量 print(os.name)#当前系统名称 print(os.path.abspath(__file__))#获取绝对路径 print(os.path.split("/usr/hehe/hehe.txt"))#分割路径和文件名 print(os.path.dirname("/usr/local"))#获取父目录 print(os.path.basename("/usr/local"))#获取最后一级,如果是文件显示文件名,如果是目录显示目录名 print(os.path.exists("/usr/local"))#目录/文件是否存在 print(os.path.isabs("."))#判断是否是绝对路径 print(os.path.isfile("/usr/local"))#判断是否是一个文件 print(os.path.isdir("/usr/local"))#是否是一个路径 print(os.path.join("/root",'hehe','a.sql'))#拼接成一个路径 print(os.path.getatime("len_os.py"))#输出最近访问时间 print(os.path.getmtime("len_os.py"))#输出最近访问时间

    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]#获取输入的值

    三、random模块

        import random,string    
        print(random.random())#随机浮点数,默认取0-1,不能指定范围
        print(random.randint(1,20))#随机整数
        print(random.randrange(1,20))#随机产生一个range
        print(random.choice('x23serw4'))#随机取一个元素
        print(random.sample('hello',2))#从序列中随机取几个元素
        print(random.uniform(1,9))#随机取浮点数,可以指定范围
        x = [1,2,3,4,6,7]
        random.shuffle(x)#洗牌,打乱顺序,会改变原list的值
        print(x)
        print(string.ascii_letters+string.digits)#所有的数字和字母

    四、time&datetime模块

    time和datetime模块主要用于操作时间

    时间有三种表示方式,一种是时间戳、一种是格式化时间、一种是时间元组

            import datetime,time        
            print(time.timezone)#和标准时间相差的时间,单位是s
            print(time.time())#获取当前时间戳
            print(time.sleep(1))#休息几s
            print(time.gmtime())#把时间戳转换成时间元组,如果不传的话,默认取标准时区的时间戳
            print(time.localtime())#把时间戳转换成时间元组,如果不传的话,默认取当前时区的时间戳
            print(time.mktime(time.localtime()))#把时间元组转换成时间戳
            print(time.strftime("%y%m%d %H%M%S"))#将时间元组转换成格式化输出的字符串
            print(time.strptime("20160204 191919","%Y%m%d %H%M%S"))#将格式化的时间转换成时间元组
            print(time.struct_time)#时间元组
            print(time.asctime())#时间元转换成格式化时间
            print(time.ctime())#时间戳转换成格式化时间
            print(datetime.datetime.now())#当然时间格式化输出
            print(datetime.datetime.now()+datetime.timedelta(3))#3天后的时间
            print(datetime.datetime.now()+datetime.timedelta(-3))#3天前的时间

    五、shelve模块

    shelve模块用来持久化存储数据,比起json来,json只能存储list、字典这样的数据类型,如果是一个函数,一个类的话,就没有办法存储了,但是shelve模块可以,shelve模块是key-value存储的,value是你存储的内容,使用如下

            
            import hashlib
             
            m = hashlib.md5()
            m.update(b"Hello")
            m.update(b"It's me")
            print(m.digest())
            m.update(b"It's been a long time since last time we ...")
             
            print(m.digest()) #2进制格式hash
            print(len(m.hexdigest())) #16进制格式hash
            # ######## md5 ########
             
            hash = hashlib.md5()
            hash.update('admin')
            print(hash.hexdigest())
            # ######## sha1 ########
             
            hash = hashlib.sha1()
            hash.update('admin')
            print(hash.hexdigest())
            # ######## sha256 ########
             
            hash = hashlib.sha256()
            hash.update('admin')
            print(hash.hexdigest())
             
            # ######## sha384 ########
             
            hash = hashlib.sha384()
            hash.update('admin')
            print(hash.hexdigest())
            # ######## sha512 ########
             
            hash = hashlib.sha512()
            hash.update('admin')
            print(hash.hexdigest())

    七、configparser模块

    configparser模块用来操作配置文件,用于生成和修改常见配置文档,python 3.x 中为configparser,python2中为ConfigParser。

    一个常见的配置文件如下:

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

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

        import 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.read('my.cnf')
        sections = config.sections()#获取所有节点
        print(config.get('bitbucket.org','User'))#取对应节点下面key的值
        config.add_section('NEW')#增加节点
        config.set('NEW','test','true')#增加节点下面对应的熟悉和值
        config.set('DEFAULT','niu','222222')#修改节点下的属性
        config.write(open("my.cnf","w"))#写入修改后的文件
        config.has_option('NEW','test')#节点下是否有对应的属性
        config.has_section('NEW')#是否有该节点
        config.remove_section('NEW')#删除节点
        config.remove_option('NEW','test')#删除节点下面的key

    八、re模块

    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() 结果 '	'

    常用的匹配语法

            re.match 从头开始匹配        
            re.search 匹配包含
            re.findall 把所有匹配到的字符放到以列表中的元素返回
            re.splitall 以匹配到的字符当做列表分隔符
            re.sub      匹配字符并替换
  • 相关阅读:
    结巴分词 0.14 版发布,Python 中文分词库
    Lazarus 1.0.2 发布,Pascal 集成开发环境
    Android全屏 去除标题栏和状态栏
    服务器日志现 Android 4.2 传将添多项新特性
    Percona XtraBackup 2.0.3 发布
    长平狐 Android 强制设置横屏或竖屏 设置全屏
    NetBeans 7.3 Beta 发布,全新的 HTML5 支持
    CppDepend现在已经支持Linux
    GromJS 1.7.18 发布,服务器端的 JavaScript
    Apache OpenWebBeans 1.1.6 发布
  • 原文地址:https://www.cnblogs.com/hanzhao1987/p/8203638.html
Copyright © 2011-2022 走看看