python_day5

模块,用一砣代码实现了某个功能的代码集合。 

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

常用的模块

1、time&datetime模块

    

 1 #Author : Felix Li
 2 
 3 import time
 4 
 5 x=time.time()    # 时间戳  ( 从1970年到当前的秒数 unix 开始的时间)
 6 print(x)
 7 
 8 time.sleep(1)
 9 y=time.clock()       #从进程开始,返回CPU的时间
10 print(y)
11 
12 
13 print(time.gmtime())  #时间戳转成struct_time ,结果为UTC时区
14 z=time.localtime()    #时间戳转成struct_time ,结果为本地时区
15 print(z)
16 
17 print(time.mktime(z))  #将struct_time转成时间戳
18 
19 c=time.strftime("%Y-%m-%d %H:%M:%S",z)   #将struct_time转成格式化的字符串形式
20 print(c)
21 
22 print(time.strptime("2018/01/31 14:42:01","%Y/%m/%d %H:%M:%S"))  #将格式化的字符串转成struct_time
time

 

 1 #Author : Felix Li
 2 
 3 import datetime
 4 
 5 print(datetime.datetime.now())      #当前时间
 6 
 7 print(datetime.datetime.now() + datetime.timedelta(3))  #默认的是day
 8 
 9 print(datetime.datetime.now()+datetime.timedelta(-15))     #当前时间的前15 day
10 
11 print(datetime.datetime.now()+datetime.timedelta(hours=3)) #当前时间+3 hours
12 
13 print(datetime.datetime.now()+datetime.timedelta(minutes=3))  #当前时间+3 分钟
datetime

2、random模块

 

1 #Author : Felix Li
2 
3 import random
4 
5 print(random.random())    #随机生成(0,1)之间的浮点数,顾头不顾尾!
6 
7 print(random.randint(0,2))  #随机生成整数0,1,2
8 
9 print(random.randrange(0,2))  #随机生成0,1    和range 一样 顾头不顾尾!
random

 

 1 #Author : Felix Li
 2 
 3 import random
 4 
 5 checkcode=''
 6 
 7 for i in range(5):
 8     current=random.randrange(0,5)
 9     if current==i:
10         number=chr(random.randint(97,122))
11     elif current>i:
12         number=chr(random.randint(65,90))
13     else:
14         number=random.randint(0,9)
15     checkcode+=str(number)
16 print(checkcode)
随机验证码

3、os模块

 提供对操作系统进行调用的接口

 

 1 #Author : Felix Li
 2 #  os模块  还得练习
 3 
 4 import os
 5 
 6 print(os.getcwd())  #获取当前工作目录,,即当前脚本工作目录
 7 
 8 print(os.chdir(''))  #改变当前工作脚本
 9 
10 print(os.curdir)
os

4、shutil模块

    复制、压缩、解压文件 

 

 1 #Author : Felix Li
 2 
 3 import shutil  #复制的作用
 4 
 5 
 6 f1=open('file_1',encoding="utf-8")
 7 f2=open('file_2','w',encoding="utf-8")
 8 shutil.copyfileobj(f1,f2)
 9 
10 
11 shutil.copyfile("file_1","feil_3")
12 
13 
14 shutil.rmtree("feil_3") #删除文件
15 
16 
17 
18 '''压缩文件 解压文件'''
19 import zipfile
20 z=zipfile.ZipFile('day5.zip','w')
21 z.write("os_test")
22 print('-------')
23 z.write("shutil_test")
24 z.close()
shutil

 

5、shelve模块

 

 1 #Author : Felix Li
 2 import shelve   #可以持久化任何pickle可支持的python数据格式
 3 import datetime
 4 d =shelve.open('shelve.test')
 5 
 6 print(d.get('name'))
 7 print(d.get('info'))
 8 print(d.get('date'))
 9 
10 
11 # info={'age':23,'job':'robots'}
12 #
13 # name=['felix','main','test']
14 #
15 # d['name']=name
16 # d['info']=info
17 # d['date']=datetime.datetime.now()
shelve

 

6、xml处理模块

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

 xml例子文件:

 1 <data>
 2     <country name="Liechtenstein">
 3         <rank updated="yes">2</rank>
 4         <year updated="yes">2009</year>
 5         <gdppc>141100</gdppc>
 6         <neighbor direction="E" name="Austria" />
 7         <neighbor direction="W" name="Switzerland" />
 8     </country>
 9     <country name="Singapore">
10         <rank updated="yes">5</rank>
11         <year updated="yes">2012</year>
12         <gdppc>59900</gdppc>
13         <neighbor direction="N" name="Malaysia" />
14     </country>
15     <country name="Panama">
16         <rank updated="yes">69</rank>
17         <year updated="yes">2012</year>
18         <gdppc>13600</gdppc>
19         <neighbor direction="W" name="Costa Rica" />
20         <neighbor direction="E" name="Colombia" />
21     </country>
22 </data>
xmltest
遍历xml:
 1 #Author : Felix Li
 2 import xml.etree.ElementTree as ET
 3 
 4 tree=ET.parse('xml_text.xml')
 5 root=tree.getroot()  #读取xml文件
 6 print(root.tag)
 7 
 8 for child in root:   #遍历xml文档
 9     print(child.tag,child.attrib)
10     for i in child:
11         print(i.tag,i.text,i.attrib)
12 
13 
14 for node in root.iter('gdppc'):  #只遍历gdppc
15     print(node.tag,node.text)
xml_text

xml修改和删除:

 1 #Author : Felix Li
 2 
 3 import xml.etree.ElementTree as ET
 4 
 5 tree = ET.parse("xml_text.xml")
 6 root = tree.getroot()
 7 
 8 # 修改
 9 for node in root.iter('year'):
10     new_year = int(node.text) + 1
11     node.text = str(new_year)
12     node.set("updated", "yes")
13 
14 tree.write("xml_text.xml")
15 
16 # 删除node
17 for country in root.findall('country'):
18     rank = int(country.find('rank').text)
19     if rank > 50:
20         root.remove(country)
21 
22 tree.write('output.xml')
xml_修改和删除

 7、hashlib模块

    用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。

例子中还包括hmac(内部对我们创建key和 '内容 '进行处理然后再加密):

 1 #Author : Felix Li
 2 
 3 import hashlib
 4 
 5 m=hashlib.md5()
 6 m.update('你是250'.encode(encoding="utf-8"))
 7 print(m.digest())
 8 print(m.hexdigest())
 9 
10 
11 import hmac
12 
13 h=hmac.new('你是250'.encode(encoding="utf-8"))
14 print(h.digest())  #加密成十进制
15 print(h.hexdigest())#加密成十六进制
hashlisb

 

8、re模块(***)

 

 #Author : Felix Li

import re

 # 匹配所有字符
print(re.search(".+","we are family ! 123"))

 #匹配纯数字
print(re.search("\d+","we are family ! 123"))
 #匹配前一个字符1次或者0次
print(re.search("we are?","we are family ! 123"))
 #{m} 匹配前一个字符m次
print(re.search("[0-9]{3}","we 4 are 5 family ! 123"))
print(re.findall("[0-9]{1,3}","we 4 are 5 family ! 123"))
 #匹配左或者右的字符
print(re.search("fa|we","we are family ! 123"))
print(re.findall("we|fa|e","we are family ! 123"))
 #分组匹配
print(re.search("(ly){2}(123|456)(\|\|){3}","we are familyly123|||||| ! 123"))

 #典型 匹配身份证号  (成了一个字典)
print(re.search("(?P<province>[0-9]{2})(?P<city>[0-9]{2})(?P<county>[0-9]{2})(?P<birthday>[0-9]{8})","370123199406291018").groupdict())

 #以匹配到的字符当作列表分隔符
print(re.split("[0-9]","asd12fg44hh4rw33rr3"))
 #匹配字符并替换
print(re.sub("e","E","we are family!!!"))
View Code

 

 

 

 

 

 

posted @ 2018-04-03 20:35  任重道远21  阅读(153)  评论(0)    收藏  举报