一.time与datetime模块

1.1time

在Python中,通常有这几种方式来表示时间:

  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
  1. import time
  2. #--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
  3. print(time.time()) # 时间戳:1487130156.419527
  4. print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:'2017-02-15 11:40:53'
  5.  
  6. print(time.localtime()) #本地时区的struct_time
  7. print(time.gmtime()) #UTC时区的struct_time

1.2时间格式的相互转换

  

  1. #--------------------------按图1转换时间
  2. # localtime([secs])
  3. # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
  4. time.localtime()
  5. time.localtime(1473525444.037215)
  6.  
  7. # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
  8.  
  9. # mktime(t) : 将一个struct_time转化为时间戳。
  10. print(time.mktime(time.localtime()))#1473525749.0
  11.  
  12. # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
  13. # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
  14. # 元素越界,ValueError的错误将会被抛出。
  15. print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
  16.  
  17. # time.strptime(string[, format])
  18. # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
  19. print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
  20. #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
  21. # tm_wday=3, tm_yday=125, tm_isdst=-1)
  22. #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

  

  1. #--------------------------按图2转换时间
  2. # asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。
  3. # 如果没有参数,将会将time.localtime()作为参数传入。
  4. print(time.asctime())#Sun Sep 11 00:43:43 2016
  5.  
  6. # ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为
  7. # None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
  8. print(time.ctime()) # Sun Sep 11 00:46:38 2016
  9. print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016

1.3其它

time.sleep      # 线程推迟指定的时间运行,单位为秒

2.datetime  时间加减

  1. import datetime
  2.  
  3. # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925格式
  4. #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19
  5. # print(datetime.datetime.now() )
  6. # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
  7. # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
  8. # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
  9. # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
  10.  
  11. #
  12. # c_time = datetime.datetime.now()
  13. # print(c_time.replace(minute=3,hour=2)) #时间替换

二.random模块

  1. import random
  2.  
  3. print(random.random())#(0,1)----float 大于0且小于1之间的小数
  4.  
  5. print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之间的整数
  6.  
  7. print(random.randrange(1,3)) #[1,3) 大于等于1且小于3之间的整数
  8.  
  9. print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
  10.  
  11. print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合
  12.  
  13. print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716
  14.  
  15. item=[1,3,5,7,9]
  16. random.shuffle(item) #打乱item的顺序,相当于"洗牌"
  17. print(item)

 应用:生成随机验证码

  1. import random
  2. def make_code(n):
  3. res=''
  4. for i in range(n):
  5. s1=chr(random.randint(65,90))
  6. s2=str(random.randint(0,9))
  7. res+=random.choice([s1,s2])
  8. return res
  9.  
  10. print(make_code(9))

三.scondigparser模块

配置文件如下:

  1. # 注释1
  2. ; 注释2
  3.  
  4. [section1]
  5. k1 = v1
  6. k2:v2
  7. user=egon
  8. age=18
  9. is_admin=true
  10. salary=31

  11. [section2]
  12. k1 = v1

读取

  1. import configparser
  2.  
  3. config=configparser.ConfigParser()
  4. config.read('a.cfg')
  5.  
  6. #查看所有的标题
  7. res=config.sections() #['section1', 'section2']
  8. print(res)
  9.  
  10. #查看标题section1下所有key=value的key
  11. options=config.options('section1')
  12. print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']
  13.  
  14. #查看标题section1下所有key=value的(key,value)格式
  15. item_list=config.items('section1')
  16. print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]
  17.  
  18. #查看标题section1下user的值=>字符串格式
  19. val=config.get('section1','user')
  20. print(val) #egon
  21.  
  22. #查看标题section1下age的值=>整数格式
  23. val1=config.getint('section1','age')
  24. print(val1) #18
  25.  
  26. #查看标题section1下is_admin的值=>布尔值格式
  27. val2=config.getboolean('section1','is_admin')
  28. print(val2) #True
  29.  
  30. #查看标题section1下salary的值=>浮点型格式
  31. val3=config.getfloat('section1','salary')
  32. print(val3) #31.0

改写

  1. import configparser
  2.  
  3. config=configparser.ConfigParser()
  4. config.read('a.cfg',encoding='utf-8')
  5.  
  6. #删除整个标题section2
  7. config.remove_section('section2')
  8.  
  9. #删除标题section1下的某个k1和k2
  10. config.remove_option('section1','k1')
  11. config.remove_option('section1','k2')
  12.  
  13. #判断是否存在某个标题
  14. print(config.has_section('section1'))
  15.  
  16. #判断标题section1下是否有user
  17. print(config.has_option('section1',''))
  18.  
  19. #添加一个标题
  20. config.add_section('egon')
  21.  
  22. #在标题egon下添加name=egon,age=18的配置
  23. config.set('egon','name','egon')
  24. config.set('egon','age',18) #报错,必须是字符串
  25.  
  26. #最后将修改的内容写入文件,完成最终的修改
  27. config.write(open('a.cfg','w'))

四.OS模块

os模块是与操作系统交互的一个接口

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

  

  1. LinuxMac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。
  2. >>> os.path.normcase('c:/windows\\system32\\')
  3. 'c:\\windows\\system32\\'
  4.  
  5. 规范化路径,如..和/
  6. >>> os.path.normpath('c://windows\\System32\\../Temp/')
  7. 'c:\\windows\\Temp'
  8.  
  9. >>> a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
  10. >>> print(os.path.normpath(a))
  11. /Users/jieli/test1

  

  1. os路径处理
  2. #方式一:推荐使用
  3. import os
  4. #具体应用
  5. import os,sys
  6. possible_topdir = os.path.normpath(os.path.join(
  7. os.path.abspath(__file__),
  8. os.pardir, #上一级
  9. os.pardir,
  10. os.pardir
  11. ))
  12. sys.path.insert(0,possible_topdir)
  13.  
  14. #方式二:不推荐使用
  15. os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

五.sys模块

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

  打印进度条

  1. #=========知识储备==========
  2. #进度条的效果
  3. [# ]
  4. [## ]
  5. [### ]
  6. [#### ]
  7.  
  8. #指定宽度
  9. print('[%-15s]' %'#')
  10. print('[%-15s]' %'##')
  11. print('[%-15s]' %'###')
  12. print('[%-15s]' %'####')
  13.  
  14. #打印%
  15. print('%s%%' %(100)) #第二个%号代表取消第一个%的特殊意义
  16.  
  17. #可传参来控制宽度
  18. print('[%%-%ds]' %50) #[%-50s]
  19. print(('[%%-%ds]' %50) %'#')
  20. print(('[%%-%ds]' %50) %'##')
  21. print(('[%%-%ds]' %50) %'###')
  22.  
  23. #=========实现打印进度条函数==========
  24. import sys
  25. import time
  26.  
  27. def progress(percent,width=50):
  28. if percent >= 1:
  29. percent=1
  30. show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')
  31. print('\r%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')
  32.  
  33. #=========应用==========
  34. data_size=1025
  35. recv_size=0
  36. while recv_size < data_size:
  37. time.sleep(0.1) #模拟数据的传输延迟
  38. recv_size+=1024 #每次收1024
  39.  
  40. percent=recv_size/data_size #接收的比例
  41. progress(percent,width=70) #进度条的宽度70 

六.shutil模块

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中

  1. 1 import shutil
  2. 2
  3. 3 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

shutil.copyfile(src, dst)
拷贝文件

  1. 1 shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在

shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

  1. 1 shutil.copymode('f1.log', 'f2.log') #目标文件必须存在

shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

  1. 1 shutil.copystat('f1.log', 'f2.log') #目标文件必须存在

shutil.copy(src, dst)
拷贝文件和权限

  1. 1 import shutil
  2. 2
  3. 3 shutil.copy('f1.log', 'f2.log')

shutil.copy2(src, dst)
拷贝文件和状态信息

  1. 1 import shutil
  2. 2
  3. 3 shutil.copy2('f1.log', 'f2.log')

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹

  1. 1 import shutil
  2. 2
  3. 3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_pat

在这里::::https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label3

七.json&pickle模块

之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值。

  1. 1 import json
  2. 2 x="[null,true,false,1]"
  3. 3 print(eval(x)) #报错,无法解析null类型,而json就可以
  4. 4 print(json.loads(x)) 

什么是序列化?

我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。

为什么要序列化?

1:持久保存状态

需知一个软件/程序的执行就在处理一系列状态的变化,在编程语言中,'状态'会以各种各样有结构的数据类型(也可简单的理解为变量)的形式被保存在内存中。

内存是无法永久保存数据的,当程序运行了一段时间,我们断电或者重启程序,内存中关于这个程序的之前一段时间的数据(有结构)都被清空了。

在断电或重启程序之前将程序当前内存中所有的数据都保存下来(保存到文件中),以便于下次程序执行能够从文件中载入之前的数据,然后继续执行,这就是序列化。

具体的来说,你玩使命召唤闯到了第13关,你保存游戏状态,关机走人,下次再玩,还能从上次的位置开始继续闯关。或如,虚拟机状态的挂起等。

2:跨平台数据交互

序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发的双方约定好实用一种序列化的格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互。

反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。

如何序列化之json和pickle:

json

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:

  1. 1 import json
  2. 2
  3. 3 dic={'name':'alvin','age':23,'sex':'male'}
  4. 4 print(type(dic))#<class 'dict'>
  5. 5
  6. 6 j=json.dumps(dic)
  7. 7 print(type(j))#<class 'str'>
  8. 8
  9. 9
  10. 10 f=open('序列化对象','w')
  11. 11 f.write(j) #-------------------等价于json.dump(dic,f)
  12. 12 f.close()
  13. 13 #-----------------------------反序列化<br>
  14. 14 import json
  15. 15 f=open('序列化对象')
  16. 16 data=json.loads(f.read())# 等价于data=json.load(f)
  17.  
  18. #注意
  19. import json
  20. #dct="{'1':111}"#json 不认单引号
  21. #dct=str({"1":111})#报错,因为生成的数据还是单引号:{'one': 1}
  22.  
  23. dct='{"1":"111"}'
  24. print(json.loads(dct))
  25.  
  26. #conclusion:
  27. # 无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads
  28.  
  29. #了解
  30. # 在python解释器2.7与3.6之后都可以json.loads(bytes类型),但唯独3.5不可以
  31. >>> import json
  32. >>> json.loads(b'{"a":111}')
  33. Traceback (most recent call last):
  34. File "<stdin>", line 1, in <module>
  35. File "/Users/linhaifeng/anaconda3/lib/python3.5/json/__init__.py", line 312, in loads
  36. s.__class__.__name__))
  37. TypeError: the JSON object must be str, not 'bytes'
  38.  
  39. #猴子补丁与ujson
  40. # 一.什么是猴子补丁?
  41. 属性在运行时的动态替换,叫做猴子补丁(Monkey Patch)。
  42. 猴子补丁的核心就是用自己的代码替换所用模块的源代码,详细地如下
  43.   1,这个词原来为Guerrilla Patch,杂牌军、游击队,说明这部分不是原装的,在英文里guerilla发音和gorllia(猩猩)相似,再后来就写了monkey(猴子)。
  44.   2,还有一种解释是说由于这种方式将原来的代码弄乱了(messing with it),在英文里叫monkeying about(顽皮的),所以叫做Monkey Patch
  45.  
  46. # 二. 猴子补丁的功能(一切皆对象)
  47.   1.拥有在模块运行时替换的功能, 例如: 一个函数对象赋值给另外一个函数对象(把函数原本的执行的功能给替换了)
  48. class Monkey:
  49. def hello(self):
  50. print('hello')
  51.  
  52. def world(self):
  53. print('world')
  54.  
  55. def other_func():
  56. print("from other_func")
  57.  
  58. monkey = Monkey()
  59. monkey.hello = monkey.world
  60. monkey.hello()
  61. monkey.world = other_func
  62. monkey.world()
  63.  
  64. # 三.monkey patch的应用场景
  65. 如果我们的程序中已经基于json模块编写了大量代码了,发现有一个模块ujson比它性能更高,
  66. 但用法一样,我们肯定不会想所有的代码都换成ujson.dumps或者ujson.loads,那我们可能
  67. 会想到这么做
  68. import ujson as json,但是这么做的需要每个文件都重新导入一下,维护成本依然很高
  69. 此时我们就可以用到猴子补丁了
  70. 只需要在入口处加上
  71. , 只需要在入口加上:
  72.  
  73. import json
  74. import ujson
  75.  
  76. def monkey_patch_json():
  77. json.__name__ = 'ujson'
  78. json.dumps = ujson.dumps
  79. json.loads = ujson.loads
  80.  
  81. monkey_patch_json() # 之所以在入口处加,是因为模块在导入一次后,后续的导入便直接引用第一次的成果
  82.  
  83. #其实这种场景也比较多, 比如我们引用团队通用库里的一个模块, 又想丰富模块的功能, 除了继承之外也可以考虑用Monkey
  84. Patch.采用猴子补丁之后,如果发现ujson不符合预期,那也可以快速撤掉补丁。个人感觉Monkey
  85. Patch带了便利的同时也有搞乱源代码的风险!

八.shelve模块

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

  1. import shelve
  2.  
  3. f=shelve.open(r'sheve.txt')
  4. # f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
  5. # f['stu2_info']={'name':'gangdan','age':53}
  6. # f['school_info']={'website':'http://www.pypy.org','city':'beijing'}
  7.  
  8. print(f['stu1_info']['hobby'])
  9. f.close()

  

九.Xml模块

https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label3

十.hashlib模块

# 1、什么叫hash:hash是一种算法(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算法接受传入的内容,经过运算得到一串hash值

# 2、hash值的特点是:

#2.1 只要传入的内容一样,得到的hash值必然一样=====>要用明文传输密码文件完整性校验

#2.2 不能由hash值返解成内容=======》把密码做成hash值,不应该在网络传输明文密码

#2.3 只要使用的hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的

hash算法就像一座工厂,工厂接收你送来的原材料(可以用m.update()为工厂运送原材料),经过加工返回的产品就是hash值

十一.suprocess模块

https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label3

十二.logging模块

https://www.cnblogs.com/linhaifeng/articles/6384466.html#_label3

十三.re模块

一:什么是正则?

 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

二:常用匹配模式(元字符)

http://blog.csdn.net/yufenghyc/article/details/51078107

  1. # =================================匹配模式=================================
  2. #一对一的匹配
  3. # 'hello'.replace(old,new)
  4. # 'hello'.find('pattern')
  5.  
  6. #正则匹配
  7. import re
  8. #\w与\W
  9. print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
  10. print(re.findall('\W','hello egon 123')) #[' ', ' ']
  11.  
  12. #\s与\S
  13. print(re.findall('\s','hello egon 123')) #[' ', ' ', ' ', ' ']
  14. print(re.findall('\S','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
  15.  
  16. #\n \t都是空,都可以被\s匹配
  17. print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']
  18.  
  19. #\n与\t
  20. print(re.findall(r'\n','hello egon \n123')) #['\n']
  21. print(re.findall(r'\t','hello egon\t123')) #['\n']
  22.  
  23. #\d与\D
  24. print(re.findall('\d','hello egon 123')) #['1', '2', '3']
  25. print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
  26.  
  27. #\A与\Z
  28. print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
  29. print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$
  30. ^
  31. 指定匹配必须出现在字符串的开头或行的开头。
  32.  
  33. \A
  34. 指定匹配必须出现在字符串的开头(忽略 Multiline 选项)。
  35.  
  36. $
  37. 指定匹配必须出现在以下位置:字符串结尾、字符串结尾的 \n 之前或行的结尾。
  38.  
  39. \Z
  40. 指定匹配必须出现在字符串的结尾或字符串结尾的 \n 之前(忽略 Multiline 选项)。
  41.  
  42. #^与$
  43. print(re.findall('^h','hello egon 123')) #['h']
  44. print(re.findall('3$','hello egon 123')) #['3']
  45.  
  46. # 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
  47. #.
  48. print(re.findall('a.b','a1b')) #['a1b']
  49. print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
  50. print(re.findall('a.b','a\nb')) #[]
  51. print(re.findall('a.b','a\nb',re.S)) #['a\nb']
  52. print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样
  53.  
  54. #*
  55. print(re.findall('ab*','bbbbbbb')) #[]
  56. print(re.findall('ab*','a')) #['a']
  57. print(re.findall('ab*','abbbb')) #['abbbb']
  58.  
  59. #?
  60. print(re.findall('ab?','a')) #['a']
  61. print(re.findall('ab?','abbb')) #['ab']
  62. #匹配所有包含小数在内的数字
  63. print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']
  64.  
  65. #.*默认为贪婪匹配
  66. print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
  67.  
  68. #.*?为非贪婪匹配:推荐使用
  69. print(re.findall('a.*?b','a1b22222222b')) #['a1b']
  70.  
  71. #+
  72. print(re.findall('ab+','a')) #[]
  73. print(re.findall('ab+','abbb')) #['abbb']
  74.  
  75. #{n,m}
  76. print(re.findall('ab{2}','abbb')) #['abb']
  77. print(re.findall('ab{2,4}','abbb')) #['abb']
  78. print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
  79. print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'
  80.  
  81. #[]
  82. print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
  83. print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
  84. print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
  85. print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
  86. print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']
  87.  
  88. #\# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
  89. print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
  90. print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c']
  91.  
  92. #():分组
  93. print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
  94. print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
  95. print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
  96. print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
  97. print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"']
  98.  
  99. #|
  100. print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
  101. 复制代码
  102.  
  103. 复制代码
  104. # ===========================re模块提供的方法介绍===========================
  105. import re
  106. #1
  107. print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
  108. #2
  109. print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
  110.  
  111. #3
  112. print(re.match('e','alex make love')) #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
  113.  
  114. #4
  115. print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
  116.  
  117. #5
  118. print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有
  119. print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
  120. print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
  121. print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex
  122.  
  123. print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数
  124.  
  125. #6
  126. obj=re.compile('\d{2}')
  127.  
  128. print(obj.search('abc123eeee').group()) #12
  129. print(obj.findall('abc123eeee')) #['12'],重用了obj
  130. 复制代码
  131.  
  132. 复制代码
  133. import re
  134. print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) #['h1']
  135. print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1>
  136. print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1>
  137.  
  138. print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group())
  139. print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group())
  140. 复制代码
  141. 复制代码
  142. #补充二
  143. import re
  144.  
  145. #使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,所有即使匹配成功小数也不会存入结果
  146. #而不是小数时,就去匹配(-?\d+),匹配到的自然就是,非小数的数,在此处即整数
  147. #
  148. print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整数['1', '-2', '60', '', '5', '-4', '3']
  149.  
  150. #找到所有数字:
  151. print(re.findall('\D?(\-?\d+\.?\d*)',"1-2*(60+(-40.35/5)-(-4*3))")) # ['1','2','60','-40.35','5','-4','3']
  152.  
  153. #计算器作业参考:http://www.cnblogs.com/wupeiqi/articles/4949995.html
  154. expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
  155.  
  156. content=re.search('\(([\-\+\*\/]*\d+\.?\d*)+\)',expression).group() #(-3-40.0/5)

  

  1. #为何同样的表达式search与findall却有不同结果:
  2. print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)
  3. print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3']
  4.  
  5. #看这个例子:(\d)+相当于(\d)(\d)(\d)(\d)...,是一系列分组
  6. print(re.search('(\d)+','123').group()) #group的作用是将所有组拼接到一起显示出来
  7. print(re.findall('(\d)+','123')) #findall结果是组内的结果,且是最后一个组的结果
  8. 复制代码
  9.  
  10. 复制代码
  11. #_*_coding:utf-8_*_
  12. __author__ = 'Linhaifeng'
  13. #在线调试工具:tool.oschina.net/regex/#
  14. import re
  15.  
  16. s='''
  17. http://www.baidu.com
  18. egon@oldboyedu.com
  19. 你好
  20. 010-3141
  21. '''
  22.  
  23. #最常规匹配
  24. # content='Hello 123 456 World_This is a Regex Demo'
  25. # res=re.match('Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo',content)
  26. # print(res)
  27. # print(res.group())
  28. # print(res.span())
  29.  
  30. #泛匹配
  31. # content='Hello 123 456 World_This is a Regex Demo'
  32. # res=re.match('^Hello.*Demo',content)
  33. # print(res.group())
  34.  
  35. #匹配目标,获得指定数据
  36.  
  37. # content='Hello 123 456 World_This is a Regex Demo'
  38. # res=re.match('^Hello\s(\d+)\s(\d+)\s.*Demo',content)
  39. # print(res.group()) #取所有匹配的内容
  40. # print(res.group(1)) #取匹配的第一个括号内的内容
  41. # print(res.group(2)) #去陪陪的第二个括号内的内容
  42.  
  43. #贪婪匹配:.*代表匹配尽可能多的字符
  44. # import re
  45. # content='Hello 123 456 World_This is a Regex Demo'
  46. #
  47. # res=re.match('^He.*(\d+).*Demo$',content)
  48. # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
  49.  
  50. #非贪婪匹配:?匹配尽可能少的字符
  51. # import re
  52. # content='Hello 123 456 World_This is a Regex Demo'
  53. #
  54. # res=re.match('^He.*?(\d+).*Demo$',content)
  55. # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
  56.  
  57. #匹配模式:.不能匹配换行符
  58. content='''Hello 123456 World_This
  59. is a Regex Demo
  60. '''
  61. # res=re.match('He.*?(\d+).*?Demo$',content)
  62. # print(res) #输出None
  63.  
  64. # res=re.match('He.*?(\d+).*?Demo$',content,re.S) #re.S让.可以匹配换行符
  65. # print(res)
  66. # print(res.group(1))
  67.  
  68. #转义:\
  69.  
  70. # content='price is $5.00'
  71. # res=re.match('price is $5.00',content)
  72. # print(res)
  73. #
  74. # res=re.match('price is \$5\.00',content)
  75. # print(res)
  76.  
  77. #总结:尽量精简,详细的如下
  78. # 尽量使用泛匹配模式.*
  79. # 尽量使用非贪婪模式:.*?
  80. # 使用括号得到匹配目标:用group(n)去取得结果
  81. # 有换行符就用re.S:修改模式
  82.  
  83. #re.search:会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回
  84.  
  85. # import re
  86. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  87. #
  88. # res=re.match('Hello.*?(\d+).*?Demo',content)
  89. # print(res) #输出结果为None
  90.  
  91. #
  92. # import re
  93. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  94. #
  95. # res=re.search('Hello.*?(\d+).*?Demo',content) #
  96. # print(res.group(1)) #输出结果为
  97.  
  98. #re.search:只要一个结果,匹配演练,
  99. import re
  100. content='''
  101. <tbody>
  102. <tr id="4766303201494371851675" class="even "><td><div class="hd"><span class="num">1</span><div class="rk "><span class="u-icn u-icn-75"></span></div></div></td><td class="rank"><div class="f-cb"><div class="tt"><a href="/song?id=476630320"><img class="rpic" src="http://p1.music.126.net/Wl7T1LBRhZFg0O26nnR2iQ==/19217264230385030.jpg?param=50y50&quality=100"></a><span data-res-id="476630320" "
  103. # res=re.search('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)
  104. # print(res.group(1))
  105.  
  106. #re.findall:找到符合条件的所有结果
  107. # res=re.findall('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)
  108. # for i in res:
  109. # print(i)
  110.  
  111. #re.sub:字符串替换
  112. import re
  113. content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  114.  
  115. # content=re.sub('\d+','',content)
  116. # print(content)
  117.  
  118. #用\1取得第一个括号的内容
  119. #用法:将123与456换位置
  120. # import re
  121. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  122. #
  123. # # content=re.sub('(Extra.*?)(\d+)(\s)(\d+)(.*?strings)',r'\1\4\3\2\5',content)
  124. # content=re.sub('(\d+)(\s)(\d+)',r'\3\2\1',content)
  125. # print(content)
  126.  
  127. # import re
  128. # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
  129. #
  130. # res=re.search('Extra.*?(\d+).*strings',content)
  131. # print(res.group(1))
  132.  
  133. # import requests,re
  134. # respone=requests.get('https://book.douban.com/').text
  135.  
  136. # print(respone)
  137. # print('======'*1000)
  138. # print('======'*1000)
  139. # print('======'*1000)
  140. # print('======'*1000)
  141. # res=re.findall('<li.*?cover.*?href="(.*?)".*?title="(.*?)">.*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span.*?</li>',respone,re.S)
  142. # # res=re.findall('<li.*?cover.*?href="(.*?)".*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span>.*?</li>',respone,re.S)
  143. #
  144. #
  145. # for i in res:
  146. # print('%s %s %s %s' %(i[0].strip(),i[1].strip(),i[2].strip(),i[3].strip()))

  

day13.常用模块的更多相关文章

  1. atitit 商业项目常用模块技术知识点 v3 qc29

    atitit 商业项目常用模块技术知识点 v3 qc29 条码二维码barcodebarcode 条码二维码qrcodeqrcode 条码二维码dm码生成与识别 条码二维码pdf147码 条码二维码z ...

  2. 《Ansible权威指南》笔记(3)——Ad-Hoc命令集,常用模块

    五.Ad-Hoc命令集1.Ad-Hoc命令集通过/usr/bin/ansible命令实现:ansible <host-pattern> [options]    -v,--verbose  ...

  3. python学习笔记(5)--迭代器,生成器,装饰器,常用模块,序列化

    生成器 在Python中,一边循环一边计算的机制,称为生成器:generator. 如: >>> g = (x * x for xin range(10)) >>> ...

  4. 进击的Python【第五章】:Python的高级应用(二)常用模块

    Python的高级应用(二)常用模块学习 本章学习要点: Python模块的定义 time &datetime模块 random模块 os模块 sys模块 shutil模块 ConfigPar ...

  5. Python模块之常用模块,反射以及正则表达式

    常用模块  1. OS模块 用于提供系统级别的操作,系统目录,文件,路径,环境变量等 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("di ...

  6. python学习笔记之常用模块(第五天)

    参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...

  7. day--6_python常用模块

    常用模块: time和datetime shutil模块 radom string shelve模块 xml处理 configparser处理 hashlib subprocess logging模块 ...

  8. Tengine 常用模块使用介绍

    Tengine 和 Nginx Tengine简介 从2011年12月开始:Tengine是由淘宝网发起的Web服务器项目.它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能 和特性. ...

  9. Saltstack常用模块及API

    Saltstack提供了非常丰富的功能模块,涉及操作系统的基础功能.常用工具支持等,更多模块信息可以查看官网模块介绍.也可以通过sys模块列出当前版本支持的模块. salt '*' sys.list_ ...

随机推荐

  1. java基础第12期——反射、注解

    一. 反射 反射: 将类的各个组成部分封装为其他对象. 1.1 获取class对象的方式 Class.forName("全类名"): 将字节码文件加载进内存,返回class对象 多 ...

  2. Django框架-cookie和session以及中间件

    目录 一.cookie 和 session 1.为什么会有这些技术 2. cookie 2.1 Django如何设置cookie 2.2 Django如何获取cookie 2.3 Django如何设置 ...

  3. docker仓库之harbor高可用 (三)

    基于上一篇部署完成了企业级仓库harbor的部署,今天我们来聊聊什么是harbor的高可用 Harbor 支持基于策略的 Docker 镜像复制功能,这类似于 MySQL 的主从同步,其可以实现不同的 ...

  4. linux之docker 安装 mysql

    首先进入docker : 命令:systemctl start docker 查詢一下docker的状态: 命令:docker images   现在开始安装mysql了,第一步拉取镜像 命令:doc ...

  5. docker封装vue项目并使用jenkins发布

    一.概述 vue项目可以打一个dist静态资源包,直接使用Nginx发布即可. 现在由于要上docker,需要将vue项目和nginx打成一个镜像才行. 项目结构如下: ./ ├── build │  ...

  6. PAT-1148(Werewolf )思维+数学问题

    Werewolf PAT-1148 题目的要点是不管n规模多大,始终只有两个狼人 说谎的是一个狼人和一个好人 紧紧抓住这两点进行实现和分析 #include <iostream> #inc ...

  7. 手工实现一个ThreadPoolExecutor

    以下代码的实现逻辑出自于公众号 码农翻身 <你管这破玩意叫线程池?> - PS:刘欣老师在我心中是软件技术行业的大刘. 线程池接口 public interface Executor { ...

  8. STM32F103VET6-keil工程配置-USART串口中断

    1.新建一个标准空白工程 2.设置时钟源为外部HSE时钟 1 #ifndef __SYSCLK_CONFIG_H 2 #define __SYSCLK_CONFIG_H 3 #include &quo ...

  9. 去哪找Java练手项目?

    经常有读者在微信上问我: 在学编程的过程中,看了不少书.视频课程,但是看完.听完之后感觉还是不会编程,想找一些项目来练手,但是不知道去哪儿找? 类似的问题,有不少读者问,估计是大部分人的困惑. 练手项 ...

  10. centos /bin /sbin /usr/bin /usr/sbin 目录的说明

    在linux下我们经常用到的四个应用程序的目录是/bin./sbin./usr/bin./usr/sbin .而四者存放的文件一般如下:    bin目录:  bin为binary的简写主要放置一些系 ...