zoukankan      html  css  js  c++  java
  • NO.5:自学python之路------标准库,正则表达式

    引言

      时间过的好快呀,终于6级也考完了,学习Python的进度也得赶赶了。好的开始这一周的内容。

    正文

    模块

      模块的本质就是‘.py’结尾的文件,它可以用来从逻辑上组织Python代码,它可以是变量、函数、类或者逻辑,主要用来实现某一个功能。如文件名为‘test.py’的模块,那么它的模块名就为‘test’。模块与包不同,包是用来从逻辑上组织文件的,包的本质就是一个目录,,但是必须带有一个名为‘__init__.py’的文件。模块的导入方法,例子。

    import test

    import

      import某一个模块,其实就是将该模块文件中所有代码解释后赋值给模块名。它可以与from组合,例子。

    from test import function

      组合后的功能,其实就是将‘test.py’中的function部分取出,并执行。导入模块的本质就是将(sys.path搜索路径下的)某个Python文件解释一遍。导入包的本质就是解释包目录下的’__init__.py‘文件。

      注意,在包下的’__init__.py‘文件中,直接使用import无法导入包内的模块。正确导入方法,例子。

    #__init__.py
    from . import test#从绝对路径下导入
    
    #main.py
    import package
    package.test()#调用

    分类

      模块主要分为三类:标准库、开源模块和自定义模块。

      标准库是Python为编程人员提供的库,可以直接导入调用使用。如os,sys等

      开源模块是开发者开发的开源Python模块,可以从网络下载安装后使用。如numpy,pandas等

      自定义模块是自己编程的模块。

      下面将详细介绍一些常用的标准库。

    time

       时间的格式主要有三种:struc_time格式、时间戳格式以及固定格式化的格式。

    import time
    time.localtime()#UTC全国标准时间,struct_time格式
    time.timezone#与标准时间的差值,时间戳格式,单位s
    time.daylight#是否使用夏令时
    time.sleep()#停几秒
    time.gmtime()#时间戳转换为struct_time格式的UTC时间
    time.localtime()#时间戳转换为struct_time格式的当前时区时间(UTC+8)
    time.mktime()#struct_time格式转换为时间戳
    time.strftime('%Y-%m-%d %H:%M:%S',x)%将struct_time转换为格式化字符串时间
    time.strptime('2018-11-1 5:21:10','%Y-%m-%d %H:%M:%S')#将格式化时间转换为struct_time格式
    time.asctime()#当前时间(默认)或结构化元组时间转换为英文显示
    time.ctime()#当前时间(默认)或时间戳转换为英文显示
    View Code

    datatime

    import datetime
    datetime.datetime.now()#当前日期时间
    datetime.datetime.now()-datetime.timedelta(3)#默认是天
    datetime.datetime.now()-datetime.timedelta(hours=3)#3小时前
    View Code

    random

    import random
    random.random()#随机[0~1)之间的浮点数
    random.randint(1,10)#[1~10]之间随机整数
    random.randrange(1,10)#[1~10)之间随机整数
    random.choice('hello word!')#从中随机取一个值
    random.sample('hello word!',2)#从中随机取给定个数个
    random.uniform(1,10)#[1~10]之间随机浮点数
    x = [1,2,3,4,5]
    random.shuffle(x)#x洗牌
    View Code

    os

    import os
    os.getcwd()#获取当前的目录
    os.chdir(r'C:user')#转移到其他目录
    os.curdir#当前目录
    os.pardir#上一级目录
    os.makedirs(r'C:ac')#递归创建目录
    os.removedirs(r'C:ac')#如果为空则递归到上层并删除
    os.mkdir(r'C:ac')#不递归,创建目录
    os.rmdir(r'C:ac')#不递归,删除目录
    os.listdir('.')#当前目录下所有文件
    os.remove()#删除一个文件
    os.rename('oldname','newname')#重命名
    os.stat(r'C:a.jpg')#文件信息
    os.sep#win下分割符为\ linux下分割符为/
    os.linesep#终止符win下分割符为
     linux下分割符为
    
    os.pathsep#当前平台路径的分割符号 win;
    os.name#当前系统名
    os.system()#执行命令
    os.environ#获取环境变量
    os.path.abspath()#获取某个文件绝对路径
    os.path.split()#将路径中的文件夹和文件名分割
    os.path.dirname()#将路径中的文件夹和文件名分割后的目录名
    os.path.basename()#将路径中的文件夹和文件名分割后的文件名
    os.path.exists()#判断路径是否存在
    os.path.isabs()#是否为绝对路径
    os.path.isfile()#判断是否为文件
    os.path.isdir()#判断是否为目录
    os.path.join(r'C:',r'a')#将多个路径组合返回
    os.path.getatime()#获取文件最后的存取时间
    os.path.getmtime()#获取文件最后的修改时间
    View Code

    sys

    import sys
    sys.argv#命令行参数list
    sys.exit(n)#退出程序,0
    sys.version#python版本信息
    sys.path#搜索路径
    sys.platform#操作系统平台名称
    sys.stdout.write('please:')#可用于写进度条
    View Code

    shutil

    import shutil#文件、文件夹、压缩包处理
    shutil.copyfileobj(源文件对象,目标文件对象[,length])
    f1,f2 = open('test1',encoding='utf-8'),open('test2','w',encoding='utf-8')
    shutil.copyfileobj(f1,f2)
    shutil.copyfile('test1','test2')
    shutil.copystat('test1','test2')#复制文件状态和权限
    shutil.copy('test1','test2')#复制文件和权限
    shutil.copy2('test1','test2')#复制文件和状态
    shutil.copytree('test1','test2')#递归复制,复制目录下所有文件
    shutil.rmtree('test2')#递归删除,删除目录下所有文件
    shutil.move('test1','test2')#递归的移动文件
    shutil.make_archive('压缩包文件名或路径','压缩包种类zip,tar')
    View Code

    zipfile/tarfile

    import zipfile
    z = zipfile.ZipFile('test.zip','w')
    z.write('test1.py')
    z.close()
    z = zipfile.ZipFile('test.zip','r')
    z.extractall()
    z.close()
    View Code

    shelve

    import shelve#内存数据持久化模块
    d = shelve.open('test')
    class test(object):
        def __init__(self,n):
            self.n = n
    t = test(123)
    t2 = test(1233)
    name = ['aa','bb','cc']
    d['test'] = name #持久化列表
    d['t1'] = t #持久化类
    d['t2'] = t2
    d.close()
    d = shelve.open('test')#打开shelve
    d.get('t1')#读出t1
    View Code

    configparser

    import configparser#配置文档
    #生成
    config = configparser.ConfigParser()
    config['DEFAULT'] = {'LALAL':'23','AAFF':'22'
    }
    config['NEW'] = {}
    with open('test.ini','w') as configfile:
       config.write(configfile)
    #读取
    config = configparser.ConfigParser()
    config.read('test.ini')
    config.sections()#打印节点
    config['new']['lala']
    #删除
    sec = conf.remove_section('NEW')
    conf.write(open('test.ini','w'))
    View Code

    hashlib

    import hashlib#hashlib用于加密,md5
    m = hashlib.md5()
    m.update(b'hello')
    m.update(b'new')
    print(m.hexdigest())#sha1sha512sha256....
    View Code

    hmac

    import hmac
    h = hmac.new(b'key','信息'.encode(encoding=utf-8))
    print(h.digest())
    print(h.hexdigest())
    View Code

    正则表达式re

    import re
    #匹配规则:
    #'.'匹配除'
    '以外的任意字符,指定flag DOTALL可匹配任意字符;
    #'^'匹配字符开头,指定flag MULTLTNE,可以匹配('a','
    abc
    eee',flag=re.MULTILINE)
    #'$'匹配结尾
    #'*'匹配*前的字符0次或多次,re.findall('ab*','cabb3abcbaac')
    #'+'匹配前一个字符一次或多次
    #'?'匹配前一个字符1次或0次
    #'{m}'匹配前一个字符m次
    #'{n,m}'匹配前一个字符n到m次
    #'|'匹配'|'左或右的字符
    #'(...)'分组匹配
    #'A'只从字符开头匹配
    #''匹配字符结尾
    #'d'匹配数字0~9
    #'D'匹配非数字
    #'w'匹配[A-Za-z0-9]
    #'w'匹配非[A-Za-z0-9]
    #'s'匹配空白字符、	、
    、
    
    re.search()#全局搜索,取到一个后返回
    re.match()#从头搜索,取到一个后返回
    re.findall()#取出全部后返回
    re.split()#分割
    re.sub()#替换
    View Code

    作业

      Python字符串计算器

      功能:

      1.输入字符串,计算

      2.括号,乘除,优先级

    #-*- coding:utf-8 -*-
    #author: Kai Zhang
    #string calculation
    
    import re
    
    def mul(factor_1,factor_2):
        '''乘法'''
        value = float(factor_1) * float(factor_2)
        return str(value)
    
    def div(factor_1,factor_2):
        '''除法'''
        value = float(factor_1) / float(factor_2)
        return str(value)
    
    def add(factor_1,factor_2):
        '''加法'''
        value = float(factor_1) + float(factor_2)
        return str(value)
    
    def sub(factor_1,factor_2):
        '''减法'''
        value = float(factor_1) - float(factor_2)
        return str(value)
    
    def muldiv(formula):
        '''计算所有乘除'''
        formula = formula.replace('/*','/')
        formula = formula.replace('*/','/')
        muldiv_flag = True
        while muldiv_flag:
            inside = re.search('d+.?d*[*/]-?d+.?d*',formula)
            if inside:
                inside = inside.group()
                number = re.findall('d+.?d*',inside)
                if '-' in inside:
                    number[1] = '-' + number[1]
                if '*' in inside:
                    value = mul(number[0],number[1])
                else:
                    value = div(number[0],number[1])
                formula = formula.replace(inside,value)
            else:
                muldiv_flag = False
        return formula
    
    def addsub(formula):
        '''计算所有加减'''
        formula = formula.replace('--','+')
        formula = formula.replace('-+','-')
        formula = formula.replace('+-','-')
        formula = formula.replace('++','+')
        if formula[0] == '-':
            formula = '0'+formula
        addsub_flag = True
        while addsub_flag:
            inside = re.search('d+.?d*[+-]d+.?d*',formula)
            if inside:
                inside = inside.group()
                print(inside)
                number = re.findall('d+.?d*',inside)
                if '+' in inside:
                    value = add(number[0],number[1])
                else:
                    value = sub(number[0],number[1])
                formula = formula.replace(inside,value)
                print(value)
            else:
                addsub_flag = False
        return formula
    
    def calculat(formula):
        '''开括号'''
        bracket_flag = True
        result = 0
        while bracket_flag:
            inside = re.search('([d.+-*/]*)',formula)
            if inside:
                inside = inside.group()
                value = muldiv(inside.strip('()'))#去掉左右括号后计算乘除
                value = addsub(value)#计算加减
                formula = formula.replace(inside,value)
            else:
                bracket_flag = False
        value = muldiv(formula)
        result = addsub(value)#计算加减
        return float(result)
    
    if __name__ == '__main__':
        formula = input('请输入要计算的式子>>')
        formula = re.sub('s','',formula)#去掉空格
        print('>>%f'%(eval(formula)))#展示正确结果
        result = calculat(formula)#计算编程结果
        print('>>%f'%(result))#展示编程结果
    View Code
  • 相关阅读:
    MySQL中的InnoDB中产生的死锁深究
    MySQL中的触发器应用
    你除了在客户端上会使用Cookie,还能使用哪些可以作为数据缓存呢?
    js中实现输入框类似百度搜索的智能提示效果
    linux系统中启动mysql方式已经客户端如和连接mysql服务器
    linux系统安装mysql数据库
    Linux中实用的命令
    Linux下安装jdk中遇到的坑
    Git初始化配置以及配置github
    springboot中配置文件使用2
  • 原文地址:https://www.cnblogs.com/zk71124720/p/9232905.html
Copyright © 2011-2022 走看看