模块介绍:    

    模块分类:

        1、标准库

        2、开源模块

        3、自定义模块

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

    模块导入:

      1. import 模块名1,模块名2, 同时导入多个模块,模块所在位置在当前工作目录里
      2. form 模块名(文件夹名) import 变量(模块)

      3. from 模块名 import 变量(函数/模块名) as 变量(函数/模块名)#导入变量(函数/模块)并从新命

    示例·:

1 import module_test# 等于from module_test import *,调用方法不同
2 print(module_test.name)
3 module_test.sayhi()
import
1 from module_test import sayhi#导入同级文件中的某个变量,或者上级目录的文件中的某个变量(模块)
2  sayhi()#可以运行
import2
from module_test import sayhi as hello #from 模块名 import 函数名 as 新函数名
hello()
from day1 import name_list as Name_list  #from 模块名 import 模块名 as 新模块名
print(Name_list.family_name_password_list[0])
import3

    package导入:package:本质上是一个目录,必须带有一个__innit__.py文件,用来从逻辑上组织模块。package导入方法,import package名(实质是解释package下的__init__.py,并赋给package)

          导入包下的文件,从__init__.py里导入。from . import  ***.py

    示例:

1 import package_test   #import package
2 package_test.haha()#调用__init__.py下的haha()函数
3 print(package_test.name)#调用__init__.py下的name变量
import package

    导入优化:from 模块 import 函数(变量),可以减少检索模块的次数。

time 模块:

    时间的表示格式分类:

             1、格式化的时间字符串(Coordinated Universal Time)

             2、时间戳(time stamp)

             3、元组(struck_time),共九个元素

    常用使用方法:

import time
print(time.time())#打印当前时间,显示一个浮点数,单位为秒,为当前时间到1970年1月1号的时间戳
print(time.localtime())#得到一个元组,time.struct_time(tm_year=2018, tm_mon=7, tm_mday=11, tm_hour=22, tm_min=9, tm_sec=56, tm_wday=2, tm_yday=192, tm_isdst=0)
#tm_isdst=0,dst时区,代表是不是夏令时,0代表不是夏令时(Daylight Saving Time)
#UTC(Coordinated Universal Time)世界标准时间,中国为UTC+8.
#time内置变量
print(time.timezone)    #打印(0时区-当地时区)
print(time.altzone)   #打印(0UTC时间-当地时区夏令时)
print(time.daylight)#是否使用夏令时,是的话为1,否为0
#time内置函数
print(time.time())#获取时间戳
print(time.sleep(2))#delay2秒,没有返回值
print(time.gmtime(1531404079.224725))#将括号内的时间戳转化为元组形式,并且是UTC0时区的时间,当括号内不填时,默认为当前时间戳
print(time.gmtime())#将括号内的时间戳转化为元组形式,并且是UTC0时区的时间,当括号内不填时,默认为当前时间戳
print(time.localtime(1531404079.224725))#将括号内的时间戳转化为元组形式,并且是当前时区的时间,当括号内不填时,默认为当前时间
print(time.localtime())#将括号内的时间戳转化为元组形式,并且是UTC0时区的时间,当括号内不填时,默认为当前时间,type为类
a=time.localtime()
print(a.tm_year,a.tm_mday)#打印a中的元素变量
print(time.mktime(a))#将local time tuple形式转化为时间戳
print(time.strftime('%Y-%m-%d %I:%M:%S %p %A-%B',a))#将struct_time转化为格式化时间字符串,格式化含义:(%Y年,%m月,%d天,%H小时(24时制),%M分钟,%S秒, %z UTC时区,%A星期几全名,%a 星期几缩写,%B英文月份全称,%b英文月份简写,%I小时(12小时制),%p(AM或PM),%c asctime的时间格式,%j一年当中的第几天,%y去掉世纪的年份, %% ”%“字符,%w一星期中的第几天0~6)
print(time.strptime('2018-07-12 22:45:47','%Y-%m-%d %H:%M:%S'))#将格式化时间字符串转化为struct_time,与time.strftime互逆
print(time.asctime(a))#将struct_time转化为特定格式的时间字符串,格式如下:Thu Jul 12 23:01:55 2018,如果括号内没值,会传入local_time()
print(time.asctime())#将struct_time转化为特定格式的时间字符串,格式如下:Thu Jul 12 23:01:55 2018,如果括号内没值,会传入local_time()
print(time.ctime(1531404079.224725))#将时间戳转化为特定格式的时间字符串,格式如下:Thu Jul 12 23:01:55 2018,如果括号内没值,会传入local_time()
print(time.ctime())#将时间戳转化为特定格式的时间字符串,格式如下:Thu Jul 12 23:01:55 2018,如果括号内没值,会传入time.time()
time module

    格式化时间字符串的格式化含义:

                  %Y年,%m月,%d天,%H小时(24时制),%M分钟,%S秒,%z UTC时区,%A星期几全名,%a 星期几缩写,

                  %B英文月份全称,%b英文月份简写,%I小时(12小时制),%p(AM或PM),%c asctime的时间格式,

                  %j一年当中的第几天,%y去掉世纪的年份, %% ”%“字符,%w一星期中的第几天0~6

datatime 模块:

      datetime模块分为以下三类:

                  1、detatime.datetime#年月日,时秒分

                  2、datetime.time#时秒分

                  3、datetime.date#年月日

 

      内置方法:

 1 import datetime
 2 import time
 3 print(datetime.datetime.now())#获取当前时间,包括年月日时分秒eg:2018-07-12 23:22:26.986117
 4 x=time.time()
 5 print(x)
 6 print(datetime.date.fromtimestamp(x))#只获取当前日期eg:2018-07-12
 7 #时间加减
 8 print(datetime.datetime.now()+datetime.timedelta(3))#当前时间加3天
 9 print(datetime.datetime.now()+datetime.timedelta(days=-3))#当前时间减3天
10 print(datetime.datetime.now()+datetime.timedelta(hours=-3))#当前时间减3小时
11 print(datetime.datetime.now()+datetime.timedelta(minutes=30))#当前时间加30分钟
12 #时间替换
13 now_time=datetime.datetime.now()
14 print(now_time)
15 print(now_time.replace(minute=13,hour=20,year=2017,month=6,day=19,second=4))#时间替换
datetime module

os 模块:

    os模块:提供对操作系统进行调用的接口

    内置方法:

 1 import os
 2 import time
 3 print(os.getcwd())#获得当前工作目录,即当前python脚本工作的目录路径
 4 os.chdir('D:\\Python\\day2')#切换当前工作路径路径或者
 5 os.chdir(r'D:\Python\day2')#效果与上同
 6 print(os.getcwd())
 7 print(os.curdir)#当前目录"."
 8 print(os.pardir)#获取当前目录的父目录".."
 9 print(os.getcwd())
10 os.makedirs(r'D:\picture\Del\haha')#递归的创建目录,逐层创建,前面的目录存在则查找,不存在则一并创建,全部存在无法创建
11 os.removedirs(r'D:\picture\Del\haha')#目录为空则删除目录,若上层目录也为空,则也删除,递归删除,若最小子文件夹有文件会报错
12 os.mkdir(r'D:\make')#创建一级目录,若已存在则报错,若不写路径只写文件夹名则在当前工作目录下创建
13 os.mkdir(r'D:\make\mk')#在创建一级目录,若已存在则报错,若不写路径只写文件夹名则在当前工作目录下创建
14 os.rmdir(r'D:\make\mk')#删除一级目录,若存在子文件则报错,若不写路径只写文件夹名则在当前工作目录下删除
15 os.rmdir(r"D:\make")#删除一级目录,若存在子文件则报错,若不写路径只写文件夹名则在当前工作目录下删除
16 print(os.listdir(os.curdir))#将括号类名录的子文件生成一个列表
17 os.remove(r'D:\picture\wulihui.contact')#删除一个文件,必须加上文件后缀,不能删目录
18 os.rename(oldname,newname)重命名一个文件夹或文件
19 help(os.rename)
20 os.rename(r'D:\picture\图片.jpg',r'D:\picture\girl.jpg')
21 os.rename(r'D:\picture\吴礼辉',r'D:\picture\wulihui')
22 os.rename('color.py','colors.py')#不写路径默认为当前工作目录
23 print(os.stat(r'D:\picture\girl.jpg'))#获取文件或目录信息
24 print(os.sep)#输出操作系统的特定分隔符,(windows为\\,linu为/)
25 print(os.linesep)#输出当前操作系统的换行分隔符,(windows为\r\n,linux为\n)
26 print(os.environ)#查看系统所有环境变量
27 print(os.pathsep)#打印操作系统的路径分隔符,(windows为;,linux为:)
28 print(os.name)#输出字符串显示当前平台,“nt”表示windows
29 print(os.system('dir'))#执行当前系统的命令
30 #os.path
31 print(os.path.abspath(r'D:\picture\girl.jpg'))#获取文件的绝对路径
32 print(os.path.split(r'D:\picture\girl.jpg'))#生成一个元组,将目录路径和文件名分开
33 print(os.path.dirname(r'D:\picture\girl.jpg'))#返回文件的目录路径
34 print(os.path.basename(r'D:\picture\girl.jpg'))#返回文件的文件名
35 print(os.path.exists(r'D:\picture\girl.jpg'))#判断输入的路径或文件是否存在,存在未Ture
36 print(os.path.isabs(r'D:\picture\girl.jpg'))#判断是否为绝对路径,凡是某个盘开始的为绝对路径
37 print(os.path.isfile(r'D:\picture\girl.jpg'))#判断是否为一个文件,除了文件便是目录
38 print(os.path.isdir(r'D:\picture'))#判断是否为一个目录,除了文件便是目录
39 print(os.path.join(r'D:\picture',r'girl.jpg'))#将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
40 time1=os.path.getatime(r'D:\picture\girl.jpg')#返回文件或目录的最后存储时间,时间戳格式
41 print(time1)
42 print(time.ctime(time1))#转换时间表现形式
43 time2=os.path.getmtime(r'D:\picture\girl.jpg')#返回文件的最后修改时间,时间戳格式
44 print(time2)
45 print(time.ctime(time2))#转换时间表现形式
os module

    修改环境变量:

1 import sys,os
2 print(sys.path)
3 new_environment=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
4 sys.path.append(new_environment)#添加系统路径
5 from  day1 import homework2#导入文件
path

sys 模块:

    内置方法:

import sys
print(sys.argv)#命令行参数列表,第一个元素是程序本身路径,会读取脚本的参数
print(sys.version)#获取python解释器的版本信息
print(sys.maxunicode)
print(bin(sys.maxsize))#最大int值
print(sys.path)#返回文件的搜索路径,初始状态采用pythonpath环境变量的值
print(sys.platform)#返回操作系统平台名称
for i in range(4):
    sys.stdout.write('please')#不换行打印
n=0
sys.exit(n)#程序退出,正常退出时sys.exit(0)
sys moule

random 模块:

   内置方法:

 1 import random
 2 print(random.random())#随机生成[0,1)之间的一个浮点数
 3 print(random.uniform(2,4))#随机获取[2,4)之间的一个浮点数
 4 print(random.randint(1,3))#随机获取[1,3]之间的一个整数
 5 print(random.randrange(1,5,2))#随机获取range(1,5,2)之间的一个整数
 6 print(random.choice([1,2,3]))#从一个序列中随机取值,序列包括:字符串,列表,元组,不能是集合、字典
 7 print(random.sample([1,2,3,4],3))#从一个序列中随机取3个值,生成一个列表
 8 #洗牌
 9 list1=[i for i in range(1,10)]
10 print(list1)
11 random.shuffle(list1)#洗牌
12 print(list1)
random module

 

#平等的随机验证码
import random
checkcode=''
for i in range(4):
    choice=random.randint(0,63)
    if choice in range(10):
        code=str(choice)
    elif choice in range(10,36):
        code=chr(random.randint(65,90))
    else:
        code=chr(random.randint(97,122))
    checkcode+=code#字符串拼接“+”
print(checkcode)
#方法二
source_code='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
code_list=new_checkcode=random.sample(source_code,4)
#print(code_list)
checkcode2=code_list[0]+code_list[1]+code_list[2]+code_list[3]
print(checkcode2)
varification code

shelve 模块:

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

      内置方法:

 1 import shelve
 2 import datetime
 3 f=shelve.open('text2')#文件自动生成
 4 name=['diaocan','daqiao','ali']
 5 set_1={2,3,45,67,8,2}
 6 datetime_now=datetime.datetime.now()
 7 f['name']=name
 8 f['set_1']=set_1
 9 f['datetime_now']=datetime_now
10 f.close()
11 #读取文件
12 f1=shelve.open('text2')
13 for i in f1.items():
14     print(i)
15 print('--------------------------')
16 print(f1.get('name'))
17 print(f1.get('set_1'))
18 print(f1.get('datetime_now'))
shelve module

configparser 模块:

        用于生成和修改常见配置文档,与mysquel配置文件一样。

        生成配置文件:

 1 import configparser
 2 config=configparser.ConfigParser()
 3 config['DEFAULT']={'ServerAliveInterval':'45',
 4                    'compression':'yes',
 5                    'CompressionLevel':9}
 6 config['bitbucket.org']={}
 7 config['bitbucket.org']['user']='hg'
 8 config['topsecret.server.com'] = {}
 9 topsecret = config['topsecret.server.com']
10 topsecret['Host Port'] = '50022'     # mutates the parser
11 topsecret['ForwardX11'] = 'no'  # same here
12 config['DEFAULT']['ForwardX11']='YES'
13 with open('ConfigEg.ini','w',encoding='utf-8') as f:
14     config.write(f)#将文件写入ConfigEg.ini,#括号内填打开的内存对象
configparser module

        生成文件示例:

 1 [DEFAULT]
 2 serveraliveinterval = 45
 3 compressionlevel = 9
 4 compression = yes
 5 forwardx11 = YES
 6 
 7 [bitbucket.org]
 8 user = hg
 9 
10 [topsecret.server.com]
11 host port = 50022
12 forwardx11 = NO
ConfigEg.ni

        配置文件操作:

 1 import configparser
 2 config=configparser.ConfigParser()
 3 config.sections()
 4 print(config.sections())
 5 config.read('ConfigEg.ini',encoding='utf-8')
 6 print(config.sections())#不打印default_section,打印其他目录
 7 print(config.default_section)#只打印efault_sectiond
 8 print(config.defaults())#打印default下的k-v
 9 print('bitbucket.org' in config)#判断'bitbucket.org'是否在config中
10 print(config['bitbucket.org']['user'])#读取具体内容
11 #循环节点
12 for i in config['topsecret.server.com']:#还会打印default中的值,default相当于默认参数
13     print(i,config['topsecret.server.com'][i])
14 print(config['bitbucket.org']['compression'])#打印默认变量
15 print(config.options('topsecret.server.com'))#选择一个section进行打印,生成列表
16 print(config.items('topsecret.server.com'))#将key,value,组成元组,生成列表
17 print(config.get('topsecret.server.com','host port'))#获得某个元素
18 print(config.getint('topsecret.server.com','host port'))#获得某个元素,并改为整型int
19 #修改
20 config.remove_option('topsecret.server.com','host port')#移除option
21 config.remove_section('bitbucket.org')#移除section
22 config.write(open('config_test.cfg','w',encoding='utf-8'))
23 print(config.has_section('topsecret.server.com'))#判断是否有section
24 print(config.has_option('topsecret.server.com','forwardx11'))#判断是否有option
25 config.add_section('bitbucket.org')#添加section
26 config.write(open('config_test.cfg','w',encoding='utf-8'))
configparser module

xml 模块:

    xml是实现不同语言或程序之间的进行数据交换的协议,跟json差不多,但json使用起来更简单。

    xml通过<>节点来区别数据结构。

    xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml  。

    创建xml文档:

import xml.etree.ElementTree as ET

new_xml = ET.Element("personinfolist")#root节点
personinfo = ET.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"})
name =ET.SubElement(personinfo,'name')
name.text='zhaoyun'
age = ET.SubElement(personinfo, "age", attrib={"checked": "no"})
sex = ET.SubElement(personinfo, "sex")
age.text = '33'
personinfo2 = ET.SubElement(new_xml, "personinfo2", attrib={"enrolled": "no"})
name2 = ET.SubElement(personinfo2, "name")
age2 = ET.SubElement(personinfo2, "age")
sex2 = ET.SubElement(personinfo2, "sex")
age2.text = '19'
name2.text='xiaoqiao'

et = ET.ElementTree(new_xml)  # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)#xml_declaration=True声明为XML格式

ET.dump(new_xml)  # 打印生成的格式
creat XML file

    xml文档操作:

import xml.etree.ElementTree as ET
tree=ET.parse('xmleg.xml')
root=tree.getroot()
print(root.tag)#打印文件总标题
#遍历xml文档,文档格式:<tag attrib(k=v)>text</tag>
for child in root:
    print(child.tag,child.attrib,child.text)
    for i in child:
        print(i.tag,i.text,i.attrib)
#只遍历year节点
for node in root.iter('year'):
    print(node.tag,node.text)
#xml修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated_by", "wu")#修改node.attrib,(key,value)

tree.write("xmleg.xml")#写回原文件
#xml删除
for country in root.findall('country'):#findall()查找所有,find()查找
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)#删除某个变量

tree.write('output.xml')
xml operation

hashlib 模块:

      用于加密相关的操作,代替了MD5和sha模块。

      主要提供SHA1,SHA256,SHA224,SHA384,SHA512,MD5算法。

      内置方法示例:

 1 import hashlib
 2 #MD5hash加密方法
 3 m=hashlib.md5()#赋一个内存变量
 4 m.update(b'hello')#添加内容到m中
 5 m.update(b'It is me')
 6 print(m.digest())#2进制格式hash,生成MD5值
 7 print(m.hexdigest())#byte格式hash,生成MD5值
 8 m.update(b'I am your father')
 9 print(m.hexdigest())#16进制格式hash,生成MD5值
10 #sha1加密方法
11 n=hashlib.sha1()#赋一个内存变量,加密方法sha1.其他方法SHA256,SHA224,SHA384,SHA512与之相同。
12 n.update(b'password')
13 print(n.hexdigest())
14 #hmac加密
15 import hmac
16 x=hmac.new(b'I am wulihui','真棒'.encode(encoding='utf-8'))
17 print(x.hexdigest())
hashlib module

shutil 模块:

     主要由于copy文件,高级的 文件、文件夹、压缩包 处理模块。

     内置方法:

import shutil
#文件内容拷贝,可以是部分内容shutil.copyfileobj(复制对象,粘贴对象,lengh),参数为文件打开对象
with open('text1','r',encoding='utf-8') as f1,\
    open('text2','w',encoding='utf-8') as f2:
    shutil.copyfileobj(f1,f2)
#文件拷贝,不拷贝权限
shutil.copyfile('text1','text3')#拷贝文件,输入文件名,将text1拷贝并命名为test3
#仅拷贝权限。内容、组、用户均不变
#print(os.stat('text1').st_mode)
#print(os.stat('text2').st_mode)
shutil.copymode('text1','text3')#仅拷贝权限。内容、组、用户均不变,text1位母版
#shutil.copystat(src, dst)#拷贝状态的信息,包括:mode bits, atime, mtime, flags,src为母版
shutil.copystat('text1','text3')#拷贝状态的信息,包括:mode bits, atime, mtime, flags,src为母版,不拷贝内容
#拷贝文件和权限
shutil.copy('text1','text4')#拷贝文件和权限
#拷贝文件和状态信息
shutil.copy2('text1','text5')#拷贝文件和状态信息,,包括:mode bits, atime, mtime, flags,src为母版,不拷贝内容
#递归拷贝文件,拷贝文件夹shutil.copytree(src, dst, symlinks=False, ignore=None)
shutil.copytree(r'D:\Python\day2\day5\package_test',"copy_package")#拷贝文件夹,copy_package不能已存在
#删除目录shutil.rmtree(path[, ignore_errors[, onerror]])
shutil.rmtree('copy_package')#删除目录,可删非空文件夹
#移动文件,剪切
#shutil.move('text5',r'D:\Python\day2\day5\package_test')
#shutil.make_archive(base_name, format,...)创建压缩包并返回文件路径,例如:zip、tar
    # base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    # 如:www                        =>保存至当前路径
    # 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    # format:    压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    # root_dir:    要压缩的文件夹路径(默认当前目录)
    # owner:    用户,默认当前用户
    # group:    组,默认当前组
    # logger:    用于记录日志,通常是logging.Logger对象
shutil.make_archive(r'D:\Python\day2\day5\shutil_module\new_zip','zip',r'D:\Python\day2\day5\package_test')
#将r'D:\Python\day2\day5\package_test'压缩到r'D:\Python\day2\day5\shutil_module\new_zip',压缩方式zip
######压缩与解压
#shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的。
import  zipfile
z=zipfile.ZipFile('day4.zip','w')
z.write('text1')
z.write('text2')
z.write('new_zip.zip')#文件要带后缀
print('haowan')
z.close()
#解压
z=zipfile.ZipFile('day4.zip','r')
z.extractall('day4')#解压路径
z.close()
shutil module

 正则表达式:

      正则表达式:用来匹配字符串,模糊匹配

        常用正则表达式符号:

           '.':默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
           '^':匹配字符开头,若指定flags MULTILINE, 这种也可以匹配上(r"^a", "\nabc\neee", flags=re.MULTILINE)
           '$': 匹配字符结尾,或re.search("foo$", "bfoo\nsdfsf", flags=re.MULTILINE).group()也可以,整个字符串结尾没匹配上,则匹配失败。
          [a-z]: 代表a~z的字母,[a-zA-Z]:代表a~z和A~Z的字母
           '*': 匹配 * 号前的字符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")是匹配不到的,效果与‘^'同
           '\Z': 匹配字符结尾,同$
          '\d': 匹配数字0 - 9
          '\D': 匹配非数字
          '\w': 匹配[A - Za - z0 - 9]
           '\W': 匹配非[A - Za - z0 - 9]
          '\s': 匹配空白字符、\t、\n、\r, re.search("\s+", "ab\tc1\n3").group() 结果'\t'
           '(?P<name>...)': 分组匹配,生成一个字典,取值逐个往后取,示例:

print(re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").groupdict())
print(re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").group('city'))
View Code

          内置方法与常用示例:

 1 import re
 2 #re.match(pattern, string, flags=0)#在str的开头使用patten进行匹配,返回匹配对象,没有找到则为None
 3 m=re.match('吴礼辉\d+',"吴礼辉123,智慧")#patten必须匹配str开头
 4 print(m.group())# 通过索引或名称返回匹配的子组。 0表示返回整个匹配。
 5 #re.search(pattern, string, flags=0)#扫描字符串寻找与模式的匹配,返回匹配对象,如果未找到匹配则为None.
 6 n=re.search('辉\d+',"吴礼辉123,智慧")#patten可以从str中间开始匹配,若存在多个,只取第一个。
 7 print(n.group())
 8 n=re.search('^吴礼辉.+慧$',"吴礼辉123,智慧")#patten可以从str中间开始匹配。
 9 print(n.group())
10 print(re.search("foo$", "bfoo\nsdfsf", flags=re.MULTILINE).group())#foo匹配换行前结尾
11 n=re.search('^吴礼辉[a-z1-9]+慧',"吴礼辉abc123慧")#patten可以从str中间开始匹配.
12 print(n.group())
13 print(re.findall('patten','str'))生成一个列表,在str中找出patten的所有匹配项
14 n=re.search('aaa?',"abcdipababbaaa")#找aa,或者aaa
15 print(n.group())
16 n=re.search('[1-3]{3}',"1253456894523123456")#找3个连在一起的[1-3]之间的数字
17 print(n.group())
18 n=re.search('[1-3]{2,5}',"1253456894523123456")#找[2-5]个连在一起的[1-3]之间的数字
19 print(n.group())
20 print(re.search("abc|ABC", "ABCBabcCD").group())#'|'类似于or
21 print(re.search("ABC\|Babc", "ABC|BabcCD").group())#\表示不转译,当成字符串的一部分
22 print(re.search("(abc){2}", "abcsdabcabchehe").group())#()为组合的操作,查找abcabc
23 print(re.search("\D+", "\r\n@@@#w123ert").group())
24 print(re.findall("\s", "\r\n@@  @# w12  3\tert"))#匹配\r,\n,\t
25 print(re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").groupdict())
26 print(re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").group('city'))
27 #split(pattern, string, maxsplit=0, flags=0)按照模式的出现拆分源字符串,返回包含结果子字符串的列表。
28 print(re.split('[0-9]+','wuei2334HDJKA78uruhi80u0qu897u'))#使用数字作分隔符对原字符串进行分割
29 #sub(pattern, repl, string, count=0, flags=0)#替换匹配上的值,repl为替换后的值,count为替换次数,默认为全部替换
30 print(re.sub('[0-9]+','|','wuei2334HDJKA78uruhi80u0qu897u',3))
31 #re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)flags=re.I
32 print(re.search('aa','AA',flags=re.I).group())
33 #M(MULTILINE): 多行模式,改变'^'和'$'的行为
34 print(re.search("foo$", "bfoo\nsdfsf", flags=re.M).group())
35 #S(DOTALL): 点任意匹配模式,改变'.'的行为
36 print(re.search(".*", "bfoo\nsdfsf", flags=re.S).group())
re module