Python之模块合集(基础笔记)

常用标准库(模块):

builtins 内建函数默认加载

math 数学库

random 生成随机数

time 时间

datetime 日期和时间

hashlib 加密算法

copy 拷贝

functools 常用的工具

os 操作系统接口

re 字符串正则匹配

sys Python自身的运行环境

multiprocessing 多进程

threading 多线程

json 编码和解码

JSON对象

logging 记录日志,调试

下面简单的说一下其中一些模块的使用。

sys模块:

该模块与Python自身的运行环境相关,当导入一个模块时,Python解析器对模块位置的搜索顺序是:

1.当前目录

2.如果不在当前目录,Python则会搜索在shell变量PYTHONPATH 下的每一个目录。

3.如果都没有找到,Python会查看默认路径。UNIX下,默认路径一般为/user/local/lib/python/

  模块搜索路径存储在 system 模块的sys.path变量中。变量里包含当前目录,PYTHONPATH和由    安装过程决定的默认目录。

import sys

print(sys.path)  #模块搜索路径
print(sys.version)
print(sys.argv)  #运行程序时的参数,argv是一个列表

输出:

['D:\\python\\PyCharm\\Study-project\\Python-project', 'D:\\python\\PyCharm\\Study-project\\Python-project', 'D:\\python\\python39.zip', 'D:\\python\\DLLs', 'D:\\python\\lib', 'D:\\python', 'D:\\python\\lib\\site-packages']
3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)]
['D:/python/PyCharm/Study-project/Python-project/44_模块合集.py']

注意:sys模块下的 path是返回在列表里模块的搜索路径

                                version则会返回Python的版本号; 

                               argv其实是argument variable 参数变量的缩写,在命令行调用的时候由系统传递给程序。这个变量其实是一个List列表,argv[0] 一般是被调用的脚本文件名或全路径,和操作系统有关,argv[1]和以后就是传入的数据了。

                               getrefcount是计算变量引用的次数

time模块:

1.时间戳 time.time() #当前时间(秒的形式)

2.time.sleep(3) #程序至此暂停三秒

3.time.ctime() #当前时间(年月日时分秒的形式)

4.time.localtime() #将时间戳转换为元组的形式(当前时间详细信息显示)

5.time.mktime() #将(时间)元组转为时间戳的形式

6.time.strftime() #将元组时间 转为字符串形式

7.time.strptime() #将字符串转为元组方式

(其中,1,2,6需重点掌握)

###一些简单示例

import time
t1 = time.time()
print(t1) #程序至此的执行时间

# time.sleep(3) #程序至此暂停3秒

t2 = time.time()
print(t2)

s = time.ctime(t1)  #当前时间
print(s)

#将时间戳转换为元组的形式(当前时间详细信息显示)
loc = time.localtime(t1)
print(loc)
print(loc.tm_hour)  #可调用元组里的具体内容
print(loc.tm_mon)


#将(时间)元组转为时间戳的形式
loc = time.mktime(loc)
print(loc)  #小数点后清零

#将元组时间 转为字符串形式
s = time.strftime('%Y-%m-%d')
print(s)  #以年月日的形式打印
s = time.strftime('%Y-%m-%d %H:%M:%S')
print(s)

#将字符串转成元组的方式
t = time.strptime('2021/9/13','%Y/%m/%d')  #第一个参数为时间字符串,第二个参数为待转换的格式
print(t)

输出:

1631707824.9219255
1631707824.9219255
Wed Sep 15 20:10:24 2021
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=15, tm_hour=20, tm_min=10, tm_sec=24, tm_wday=2, tm_yday=258, tm_isdst=0)
20
9
1631707824.0
2021-09-15
2021-09-15 20:10:24
time.struct_time(tm_year=2021, tm_mon=9, tm_mday=13, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=256, tm_isdst=-1)

datetime模块:

time 时间 time里的hour,second,minute 以对象的形式存在

date 日期 date里的year,month,day 以对象形式存在

datetime 日期和时间    now()可得到当前日期和时间

timedelta 时间差 timedelta(day='',week='',...) 结合now()作加减运算得出时间差

import datetime

print(datetime.time.hour)  #返回对象
# print(time.localtime().tm_hour)

d = datetime.date(2021,9,13)
print(datetime.date.month)
print(datetime.date.ctime(d))  #年月日时分秒的形式

print(datetime.date.today())  #输出当前的日期

#时间差
timedel = datetime.timedelta(hours=2)  #定义一个时间差
print(timedel)

now = datetime.datetime.now()  #————>得到当前日期和时间
print(now)
result = now - timedel
print(result)   #当前时间减去2小时

输出:

<attribute 'hour' of 'datetime.time' objects>
<attribute 'month' of 'datetime.date' objects>
Mon Sep 13 00:00:00 2021
2021-09-15
2:00:00
2021-09-15 20:31:09.361040
2021-09-15 18:31:09.361040

时间差有许多的使用场景,例如:数据的缓存,redis.set(key,value,时间差),来说明将数据保存多长时间。

random模块:

该模块较为常见,下面直接给出例子来进行说明,该模块里的具体使用。

import random
r = random.random()  #得到一个0 ~ 1 之间的随机小数
print(r)

r = random.randrange(1,15,2) #打印一个1~15(不包含15)的随机数,步长为2仅能打印(1,3,5,7,9,11,13)
print(r)

r = random.randint(1,10) #产生一个1~10(可包含10)的随机数
print(r)

list1 = ['Tom','Jack','Lily']
r = random.choice(list1)  #choice里放的是列表,随机打印一个列表中的元素
print(r)

pai = ['红桃K','方片A','梅花5','黑桃6']
random.shuffle(pai)  #将列表元素打乱顺序(执行洗牌的动作)
print(pai)

#验证码 大小写字母与数字组合
def func():
    code = ''
    for i in range(4):
        ran1 = str(random.randint(0,9))
        ran2 = chr(random.randint(65,90))
        ran3 = chr(random.randint(97,122))
        r = random.choice([ran1,ran2,ran3])

        code +=r
    return code
r = func()
print(r)

输出:

0.49134802675703915
9
1
Lily
['方片A', '红桃K', '黑桃6', '梅花5']
01K7

random()              #产生一个0~1之间的随机小数

randrange()        #产生一个在前两个参数范围内的数,不包括第二个参数,且第三个参数为步长

randint()              #产生一个在两个参数中间的数,左右两参数均可取到

choice()               #随机选择一个列表里的元素并返回

shuffle()               #将列表里的元素打乱顺序(执行洗牌的动作)

以上为该模块的常见的用法。

hashlib模块:

hashlib里主要负责加密算法,其中有单向加密(md5,sha1,sha256)可加密解密(base64)

import hashlib

msg = '哈哈哈'
md5 = hashlib.md5(msg.encode('utf-8'))  
print(md5)   #输出为hash 对象 md5
print(md5.hexdigest())  #输出加密后的结果

sha1 = hashlib.sha1(msg.encode('utf-8'))
print(sha1.hexdigest())

sha256 = hashlib.sha256(msg.encode('utf-8'))
print(sha256.hexdigest())

输出:

<md5 _hashlib.HASH object @ 0x0000026B10C44930>
bf17f4ab50fe9cb9e90ac041351d3946
3d271de707e031c3f9f091f0faa54326da642f29
67b15dee2c458dac4a22f33e73c7db151d5b38a09d34f6a1d72215104984795c

注意:使用hashlib.md5()即可创建一个md5对象,然后使用.update(msg.encode('utf-8')),同样也可进行编码,然后hexdigest(),以16进制返回数据摘要。

数据加密常用的场景是验证登录密码。

###下面举例###

import hashlib

#验证登录密码
password = '123456'
list = []
sha256 = hashlib.sha256(password.encode('utf-8'))
list.append(sha256.hexdigest())

print(list)

pwd = input('输入密码:')
sha256 = hashlib.sha256(pwd.encode('utf-8'))  #对密码使用同样的算法进行加密
pwd = sha256.hexdigest()
print(pwd)
for i in list:
    if pwd == i:
        print('登录成功!')

输出:

输入密码:123456
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
登录成功!

使用这种方式可对密码进行简单的加密,是不是很神奇呢。

第三方模块:

一般的,第三方模块的扩展应用也是Python应用如此广泛的原因,它真的有太多库了,几乎涉及到互联网的各个领域,所以要想熟练的使用Python解决各种问题就必须要先会使用它的各种第三方模块。

说到第三方模块,必须要讲一下pip的使用,这个我在前面的文章中有作较为详细的说明,小伙伴们可以自行参考。

Python学习笔记(pip及PyCharm的相关介绍)_Naruto的博客-CSDN博客

我们可以在Terminal,命令行使用pip安装和管理第三方模块,例如我们现在想要安装pillow(图片处理),先敲入pip,再敲入 pip install pillow ,等待安装成功吧;或者我们可以更快速的在Pycharm里File-->Setting-->Projrct:Python-project-->Python Interpreter,然后再点击+号可添加库,-号是删去库。

下面使用已经安装好了的requests模块来看看它的功能。

import requests

response = requests.get('https://www.baidu.com/')  #获取页面的源代码
print(response.text)

response1 = requests.get('http://www.baidu.cn/')   #不同格式下的源代码
print(response1.text)

输出:

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§é¢</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç»å½</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">ç»å½</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ´å¤äº§å</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å³äºç¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿è¯»</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a>&nbsp;京ICPè¯030173å·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§é¢</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç»å½</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">ç»å½</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ´å¤äº§å</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å³äºç¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿è¯»</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a>&nbsp;京ICPè¯030173å·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

下面附加几个标准库里的方法:

print(chr(65))  #Unicode码---> str
print(ord('A'))   #str--->Unicode码
print(ord('中'))

输出:

A
65
20013

可见,chr()可以将Unicode码转为str的格式,

           ord()可将str格式转为Unicode码

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谁动了我的马卡龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值