推荐4个Python中最好用的模块,相信你也用过其中的几个

一.random模块

import random
# 随机小数
random.random()  # 大于0且小于1之间的小数
random.uniform(1, 3) # 大于1小于3的小数
# ----------------------------------------
# 随机整数
random.randint(1, 5) # 大于等于1且小于等于5之间的整数
random.randrange(1, 10, 2) # 大于等于1且小于10之间的奇数
# ----------------------------------------
# 随机选择一个返回
random.choice([1, '23', [4, 5]])  # 1或者23或者[4,5]

# 随机选择多个返回
random.sample([1, '23', [4, 5]], 2) # 列表元素任意2个组合
# ----------------------------------------
# 打乱列表顺序
lst = [1, 2, 3, 4, 5, 6]
random.shuffle(lst)
print(lst) # 随机顺序

案例

# 模拟随机验证码
import random
def v_code():
    code = ''
    for i in range(5):
        num = random.randint(0, 9)
        alf = chr(random.randint(65, 90))  # chr()通过序号查字符
        add = random.choice([num, alf])
        code = "".join([code, str(add)])
    return code

print(v_code())

二.日志模块

1.工作日志分四大类:

  • 系统日志:记录服务器的一些重要信息:监控系统,cpu温度,网卡流量,重要的硬件指标
  • 网站日志:访问异常,卡顿,访问量,点击率,蜘蛛爬取次数
  • 辅助开发日志:开发人员在开发项目中,利用日志进行排错,排除一些避免不了的错误(记录),辅助开发
  • 记录用户信息的日志:用户消费习惯,新闻偏好等等(数据库解决)

2.日志一般是开发者使用的

3.日志的版本

简易版

# 缺点:文件于屏幕输出只能选择一个
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
# 默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息
-------------------------------------------------
# 灵活配置日志级别,日志格式,输出位置:
import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  
  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')
-------------------------------------------------
# 参数详解
logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息

标准版

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:725638078
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import logging

logger = logging.getLogger()
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log',encoding='utf-8') 

# 再创建一个handler,用于输出到控制台 
ch = logging.StreamHandler() 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setLevel(logging.DEBUG)

fh.setFormatter(formatter) 
ch.setFormatter(formatter) 
logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 
logger.addHandler(ch) 

logger.debug('logger debug message') 
logger.info('logger info message') 
logger.warning('logger warning message') 
logger.error('logger error message') 
logger.critical('logger critical message')
------------------------------------------------
# logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。另外,可以通过:logger.setLevel(logging.Debug)设置级别,当然,也可以通过fh.setLevel(logging.Debug)单对文件流设置某个级别

旗舰版

# 优点:
# 1.自定制(通过字典的方式)日志
# 2.轮转日志的功能

import os
import logging.config

# 定义三种日志输出格式 开始

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 定义日志输出格式 结束

logfile_dir = os.path.dirname(__file__)  # log文件的目录

logfile_name = 'log.log'  # log文件名

# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)

# log配置字典
LOGGING_DIC = {
    
    
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
    
    
        'standard': {
    
    
            'format': standard_format
        },
        'simple': {
    
    
            'format': simple_format
        },
    },
    'filters': {
    
    },
    'handlers': {
    
    
        #打印到终端的日志
        'console': {
    
    
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        #打印到文件的日志,收集info及以上的日志
        'default': {
    
    
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024*1024*5,  # 日志大小 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    'loggers': {
    
    
        #logging.getLogger(__name__)拿到的logger配置
        '': {
    
    
            'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'DEBUG',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}



logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
logger = logging.getLogger(__name__)  # 生成一个log实例
logger.info('It works!')  # 记录该文件的运行状态

三.collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

1.namedtuple: 生成可以使用名字来访问元素内容的tuple(命名元组)

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p, type(p)) # Point(x=1, y=2) <class '__main__.Point'>
print(p[0]) # 1
print(p.y)  # 2

2.deque: 双向列表,双端队列,类似于列表的一种容器型的数据,插入元素和删除元素效率高

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:725638078
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from collections import deque
q = deque(['a', 1, 'c', 'd'])
print(q, type(q))
q.append('e') # 按顺序追加
q.append('f')
q.appendleft('g') # 在左边追加
q.pop()  # 默认删除最后一个
q.popleft()  # 默认删除最前面的
# 也能按照索引查询和删除

3.OrderedDict: 有序字典

d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
from collections import OrderedDict
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od)

4.defaultdict: 默认值字典

from collections import defaultdict
l1 = [11, 22, 33, 44, 55, 66, 77, 88, 99]
dic = defaultdict(list) # 创建空字典,设置默认值(可回调的对象),每次创建key的时候,如果不写value会使用默认值
for i in l1:
    if i < 66:
        dic['key1'].append(i)
    else:
        dic['key2'].append(i)
print(dic)

5.Counter: 计数器

from collections import Counter
c = Counter('SDFSDFSDXVXCFDGDFGDFGDFGDF')  # 统计每个元素的个数
print(c)

四, re模块: 正则表达式

1.什么是正则:

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

元字符 匹配内容
\w 匹配字母(包含中文)或数字或下划线
\W 匹配非字母(包含中文)或数字或下划线
\s 匹配任意的空白符
\S 匹配任意非空白符
\d 匹配数字
\D 匹配非数字
\A 与 ^ 从字符串开头匹配
\Z 与 $ 从字符串结尾开始匹配
\n 匹配一个换行符
\t 匹配一个制表符
. 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符
[…] 匹配字符组中的字符
[^…] 匹配除了字符组中的字符的所有字符
* 匹配0个或者多个左边的字符。
+ 匹配一个或者多个左边的字符。
匹配0个或者1个左边的字符,非贪婪方式。
{n} 精准匹配n个前面的表达式。
{n,m} 匹配n到m次由前面的正则表达式定义的片段,贪婪方式
a|b 匹配a或者b。
() 匹配括号内的表达式,也表示一个组

2.匹配模式举例:

import re
re.findall()
----------------------------------------------------
# 单个字符的匹配

# \W 与 \w
s = '原始tz 12*() _'
print(re.findall('\w', s))  # \w 数字,字母,下划线,中文
print(re.findall('\W', s))  # \W 除了数字,字母,下划线,中文以外的

# \s 与 \S
print(re.findall('\s', '原始tz*(_ \t \n'))  # \s 空格,\t,\n
print(re.findall('\S', '原始tz*(_ \t \n'))  # \S 除空格,\t,\n以外的

# \d 与 \D
print(re.findall('\d','1234567890 yuanshi *(_')) # \d 数字
print(re.findall('\D','1234567890 yuanshi *(_')) # \D 非数字

# \A 与 ^
print(re.findall('\Ahello', 'hello hello 原始 hell')) # 从开
print(re.findall('^hello', 'hello hello 原始 hell')) # 从开头开始匹配头开始匹配

# \Z 与 $  从结尾开始匹配
print(re.findall('hell$', 'hello hello 原始 hell'))

# \n 与 \t
print(re.findall('\t',  'hello hello 原始 \thell'))  # \t
print(re.findall('\n',  'hello hello 原始 \nhell'))  # \n

----------------------------------------------------
# 元字符匹配

# .  ?  *  +  {m,n}  .*   ,*?
# .匹配任意字符:   如果匹配成功,光标则移到匹配成功的最后的字符;如果匹配未成功,则光标向下移动一位继续匹配
print(re.findall('a.b', 'ab aab abb aaaab'))

# ? 匹配0个或者1个由左边字符定义的片段
print(re.findall('a?b', 'ab aab abb aaaab'))

# * 匹配0个或者多个由左边字符定义的片段: 满足贪婪匹配
print(re.findall('a*b', 'ab aab abb aaaab'))

# + 匹配1个或者多个由左边字符定义的片段: 满足贪婪匹配
print(re.findall('a+b', 'ab aab abb aaaab'))

# {m,n} 匹配m个至n个(包括m和n)由左边字符定义的片段
print(re.findall('a{1,5}b', 'ab aab abb aaaaab aaaaaab'))

# .* : 贪婪匹配 从头到尾
print(re.findall('a.*b', 'ab aab abb aa#aaab aaaaaab'))

# .*? 此时的?不是对左边的字符进行0次或者1次的匹配,
# 而只是针对.*这种贪婪匹配的模式进行一种限定:告知他要遵从非贪婪匹配
print(re.findall('a.*?b', 'ab aab abb aa#aaab aaaaaab'))

# []: 一个中括号可以代表一个字符
print(re.findall('a[abc]b', 'aab abb acb afb a_b'))  # [abc]中任意一个都可以
print(re.findall('a[abc][bd]b', 'aabb aaabc abd acdbb')) # =>['aabb', 'acdb']
# - : 在[]中表示范围
print(re.findall('a[0-9]b', 'a1b a2bc abd acdbb'))  # =>['a1b', 'a2b']
print(re.findall('a[A-Z]b', 'aAb a2bc abd acdbb'))  # =>['aAb']
print(re.findall('a[A-Za-z]b', 'aAb aabc abd acdbb')) # =>['aAb', 'aab']
print(re.findall('a[-*$]b', 'a-b a*bc abd acdbb')) # =>['a-b', 'a*b']
# 当想匹配 - 时,要把 - 放在最前面或最后面
# ^ : 在[]最前面表示取反
print(re.findall('a[^0-9]b', 'a1b a2bc abbd acdbb')) # =>['abb']

s = 'xiaowang_sb xiaoliu_sb wanglu_sb tianzun_sb 通天教主_nb'
print(re.findall('\w+_sb', s))


# (): 分组
s = 'xiaowang_sb xiaoliu_sb wanglu_sb tianzun_sb 通天教主_nb'
print(re.findall('(\w+)_sb', s)) # =>['xiaowang', 'xiaoliu', 'wanglu', 'tianzun'],返回()内的内容


# |: 匹配左边或右边
print(re.findall('xiao|da|tian', 'xiaoasdnfisdaiasdntian'))

# 在()分组里面加了?:,将全部的内容返回,而不是将组内的内容返回
print(re.findall('compan(y|ies)', 'Too many companies have gone bankrupt, and the next one is my company'))
print(re.findall('compan(?:y|ies)', 'Too many companies have gone bankrupt, and the next one is my company'))

-----------------------------------------------------
# 常用方法

# re.findall()  # 全部找到返回一个列表

# re.search() # 找到第一个符合条件的字符串,然后返回一个包含匹配信息的对象,通过对象.group()获取
ret = re.search('sb|qwe', 'xiaomingt sb qwe')
print(ret)
print(ret.group())
# re.match() # 从字符串开头匹配,如果以符合条件的字符串开头则返回,否则返回None
ret = re.match('sb|qwe', 'xiaomingt sb qwe')
ret2 = re.match('sb|qwe', 'sbxiaomingt sb qwe')
print(ret)
print(ret2)


# split()  # 分割
s1 = 'xiaoming,tiaoshang;太阳~地球'
print(re.split('[;,~]', s1))  # 自定义分隔符

# sub 调换
print(re.sub('me', '我', 'me是最好的男人,me就是一个普通男人,请不要将me当男神对待。'))
print(re.sub('me', '我', 'me是最好的男人,me就是一个普通男人,请不要将me当男神对待。', 2))


# compile  配置匹配规则
obj = re.compile('\d{2}')
print(obj.search('abc123eeee').group())  # => 12
print(obj.findall('abc123eeee')) # => ['12']

s1 = '''
时间就是1995-04-27,2005-04-27
1999-04-27 
 alex 1980-04-27:1980-04-27
2018-12-08
'''
print(re.findall('\d{4}-\d{2}-\d{2}', s1))

s2 = '3325783547345nvn8b8473v 2893472893'
obj = re.compile('[1-9][0-9]{4,7}')
print(obj.findall(s2))

结尾给大家推荐一个非常好的学习教程,希望对你学习Python有帮助!

Python基础入门教程推荐

Python爬虫案例教程推荐

猜你喜欢

转载自blog.csdn.net/sinat_38682860/article/details/121081415