博客园

2、常用模块 & re正则表达式

1、re 正则表达式

2、json&pickle

3、random模块

4、time与datetime

💣💣💣💣💣💣一、正则表达式💣💣💣💣💣💣

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

常用的匹配元字符

大小写字母匹配的往往是相反的

  \w      匹配字母数字和下划线   
  print(re.findall('\w','hellow_123 * _=+'))             #['h', 'e', 'l', 'l', 'o', 'w', '_', '1', '2', '3', '_']
 
   \W      匹配非 字母数字和下划线    
   print(re.findall('\W','hellow_123 * _=+'))            #[' ', '*', ' ', '=', '+']
  
  \s      匹配任意空白字符
   print(re.findall('a\sb','a b     c \n\t1234\n'))       #['a b']
 
  \S      匹配任意非空字符
  print(re.findall('a\Sb','a b     c \n\t1234\n')         #[]
  
  \d      匹配数字 
   print(re.findall('\d','aa1122, fadkf N '))            #['1','1','2','2']      
  
  \D      匹配非数字      
  print(re.findall('\d','aa1122, fadkf N '))              #['a', 'a', ',', ' ', 'f', 'a', 'd', 'k', 'f', ' ', 'N', ' ']

  \A      匹配字符串开始        
  print(re.findall('^a\wb','a_b a_c a_b'))              #['a_b']  
  
  \Z      匹配字符串结束 若存在换行,只匹配到换行前的       
   print(re.findall('ab\Z','a_b  a_c  ab'))                 #['ab']
  
  \z      匹配到字符串结束         
   print(re.findall('ab\z','a_b a_c ab'))                 #['ab']         
  
  ^       匹配字符串开头         
   print(re.findall('^a\wb','a_b a_c a_D'))               #['a_b']

  $       匹配字符串的末尾      
  print(re.findall('^liu$','liu liu'))                 #[ ]
  print(re.findall('^liu$','liu'))                     #['liu']
  
  .       匹配任意字符,除了换行符,若被re.DOTALL指定时,也可以匹配换行符             
  *       左边字符出现0或多次           
  ?       左边字符出现0或一次            
  +       左边字符出现一次或多次             
  []      用来表示一组字符串           
  [^]     不在[]中的字符            
  {n}     精确匹配n个前面的表达式        
  {n,m}   匹配n到m次前面的字符          
  a | b   匹配a或b            
  ( )     匹配括号内的表达式,也表示一个组,若想去掉()就加?:   
  
  print(re.findall('a.c',"a1c a2c aAc a\nc aaaac"))
  print(re.findall('a.c',"a1c a2c aAc a\nc aaaac",re.DOTALL))
  print(re.findall('a[1+]c',"a1c a+c aAc a\nc aaaac",re.DOTALL))
  print(re.findall('a[0-9]c',"a1c a9c a10c aAc a\nc aaaac",re.DOTALL))
  print(re.findall('a[a-z]c',"a1c a9c a10c aAc a\nc aaaac",re.DOTALL))
  print(re.findall('a[A-Z,a-z]c',"a1c a9c a10c aAc a\nc aaaac",re.DOTALL))
  print(re.findall('a[-+*/]c',"a+c a-c a*c a/c a1c a9c aAc"))
  print(re.findall('\n',"""
  a
  b
  c
  """))
  print(re.findall('a[^-+*/]c',"a+c a-c a*c a/c a1c a9c aAc"))
  ?:左边那一个字符出现0次或者1次
  print(re.findall('ab?',"b a abbbbbbbb ab"))
                                    
  *:左边那一个字符出现0次或者无穷次
  print(re.findall('ab*',"b a abbbbbbbb ab"))
                            
  +:左边那一个字符出现1次或者无穷次
  print(re.findall('ab+',"b a abbbbbbbb ab"))
                
  {n,m}:左边那一个字符出现n次或m次
  print(re.findall('ab{2,4}',"b a abbbbbbbb ab"))
                     
  print(re.findall('ab{2,4}',"b a abb abbb abbbbbbbb ab"))
  print(re.findall('a.c',"a1c a9c a10c aAc a\nc aaaac",re.DOTALL))
  print(re.findall('a[A-Z,a-z]c',"a1c a9c a10c aAc a\nc aaaac",re.DOTALL))
  print(re.findall("href='(.+?)'","< a href=' '>'我特么是百度啊'</ a>< a href='https://store.steampowered.com/'>'我特么是新浪啊'</ a>"))
                   


  print(re.findall('a.*?b','a123b ab'))
  print(re.findall('a.+?b','a123b ab'))

💣💣💣💣💣💣二、json&pickle💣💣💣💣💣💣

序列化:与反序列化 用于存档数据和跨平台交互数据

  序列化:把内存从数据中转成其他可以储存或者发送的格式
  反序列化:就是把数据从文件中提取到内存反解

温故一个小知识点

  dic = {'name':'liu'}
  with open('a.txt','wt',encoding = 'utf-8')as f:
        f.write(str(dic))   # 将字典写入硬盘
  with open('a.txt','rt',encoding = 'utf-8') as f:
        res = f.read()
        dic =eval(res)     将硬盘中的文件读取到内存 还原成字典
  以上是比较麻烦的读写方式

json

  特点:跨平台性能好,比较通用,不过只能支持一些语言共有的类型
  import json
  dic = {'name':'liu'}
  json.dump(dic,open('a.json','wt',encoding = 'utf-8')as f:
        一行代码直接写入
  dic = json.load(open('a.json','rt',encoding = 'utf-8')as f:
        print(dic) 读取

pickle

  特点:认识所有的python类型,仅限于python
  import pickle
  s = {1,2,3,4,5,6}
  s_pkl = pickle.dumps(s)    
  prickle.dump(s,open('s.pkl','wb')
  和json用法一样,不过是存成二进制格式

了解一下猴子补丁 monkey_patch_json

  json里面的dump和load功能效率不够快,就可以用ujson替换
  import json
  import ujson
  json.dump = ujson.dump
  json.dumps = ujson.dumps
  json.loads = ujson.loads
  json.load = ujson.load
  monkey_patch_json()  

💣💣💣💣💣💣三、random模块💣💣💣💣💣💣

  import random
  print(random.choice([1,2,"axx",3.1]))   choice 随机选择一个值
  print(random.sample([1,2,"axx",3.1],2))      sample 可以指定选择个数
  
  print(random.uniform(1,3))    随机生成1-3之间的小数         

  item=[1,3,5,7,9]
  random.shuffle(item)            shuddle 打乱顺序
  print(item)

简单的生成验证码

  import random

  def make_code(size = 4):
      res = ''
      for i in range(size):
          s1 = chr(random.randint(65,90))
          s2 = str(random.randint(0,9))
          res+=random.choice([s1,s2])
      return(res)
  print(make_code(4))

💣💣💣💣💣💣四,时间模块time&datetime💣💣💣💣💣💣

时间的三种格式:

  1、时间戳
        time.time()     运算时间间隔
  2、格式化时间
        time.strftime('%Y-%m-%d) 年-月-日
  3、结构化时间
        res = time.localtime    tm_year =   tm_mday =  之类

datetime

  import datetime
  print(datetime.datetime.now)  等于上面的格式化时间
  可以加减
  print(datetime.datetime.now()-datetime.datetime(day = 3.5))
posted @ 2021-01-06 15:45  小刘学python  阅读(174)  评论(0编辑  收藏  举报