模块二(时间模块,random模块,os模块,sys模块,序列化模块)

课前复习
正则表达式
元字符,量词(?)
元字符:
.
\w \d \s \W \D \S
\n \t \b
()(匹配括号内的表达式,也表示一个组) a|b(匹配字符a或者字符b,a的范围要大于b的范围)
[...](匹配字符组中的字符) [^...]
^ $
量词
? * +
{n} {n,} {n,m}
re 模块
查找:findall search match finditer #?
分割和替换:split sub subn?
编译:compile 节省时间
?到底用在了那些地方
量词:表示0次或者1次
在量词之后,是惰性匹配的标志
分组命名:(?P<name>正则表达式) 引用时(?P=name)

find/split 取消分组优先 :(?:正则表达式)?
collections
namedtuple 可命名元祖
OrderedDict 有序字典
DefaultDict 默认字典
deque 双端序列
Counter 计数器
queue 队列
先进先出FIFO

时间模块
import time
print(time.time())
print(time.sleep(0.5))
1526983083.3692863 时间戳---机器计算
以秒为单位的浮点型
1970 1 1 00 00--伦敦时间 本初子午线,时间戳的起始时间
1970 1 1 08 00--北京时间 东八区

格式化时间--字符串,给人看的
print(time.strftime('%H:%M:%S'))    #18:51:30
print(time.strftime('%y/%m/%d'))   # 18/05/22
print(time.strftime('%Y-%m-%d'))    #2018-05-22
print(time.strftime('%c'))  #Tue May 22 18:51:30 2018

结构化时间
print(time.localtime())#本地时间
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=22, tm_hour=18, tm_min=54, tm_sec=38, tm_wday=1, tm_yday=142, tm_isdst=0)
print(time.gmtime())#伦敦时间
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=22, tm_hour=10, tm_min=59, tm_sec=29, tm_wday=1, tm_yday=142, tm_isdst=0)

 

三种时间的转化方法
字符串时间<------>结构化时间<------>时间戳时间
                                    strptime                                       mktime
字符串时间(格式化时间,Format string)---------->结构化时间(元祖时间,struct_time)---------->时间戳时间(浮点时间,Timestamp)

                                   localtime(本地化时间,北京)                    strftime
时间戳时间(浮点时间,Timestamp)------------>结构化时间(元祖时间,struct_time)------------>字符串时间(格式化时间,Format string)
                                   gmtime (伦敦时间)


print(time.time())
print(time.localtime(1500000000))#time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14,...)
print(time.localtime(2000000000))#time.struct_time(tm_year=2033, tm_mon=5, tm_mday=18,...)
print(time.localtime(3000000000))#time.struct_time(tm_year=2065, tm_mon=1, tm_mday=24,...)
struct_time=time.localtime(3000000000)
print(time.mktime(struct_time))#3000000000

struct_time=time.localtime(3000000000)
ret=time.strftime('%y/%m/%d %H:%M:%S',struct_time)#格式记住,没有struct_time也可以转化成功
print(ret)#65/01/24 13:20

s_t=time.strptime('2028-5-21','%Y-%m-%d')#格式要记住
print(s_t)#time.struct_time(tm_year=2028, tm_mon=5, tm_mday=21,...)
print(time.mktime(s_t))#1842451200.0

2018-5-22 11:02:50 --时间戳1
2018-5-21 12:59:30 --时间戳2
float=时间戳1-时间戳2

import time
ftime1='2018-5-22 11:02:50'
ftime2='2018-5-21 12:59:30'
stime1=time.strptime('2018-5-22 11:02:50','%Y-%m-%d %H:%M:%S')
print(stime1)#time.struct_time(tm_year=2018, tm_mon=5, tm_mday=22, tm_hour=11, tm_min=2,tm_sec=50...)
ttime1=time.mktime(stime1)
print(ttime1)#1526958170.0
stime2=time.strptime('2018-5-21 12:59:30','%Y-%m-%d %H:%M:%S')
print(stime2)#time.struct_time(tm_year=2018, tm_mon=5, tm_mday=21, tm_hour=12, tm_min=59, tm_sec=30,...)
ttime2=time.mktime(stime2)
print(ttime2)#1526878770.0
ttime=ttime1-ttime2
stime=time.gmtime(ttime)
print(stime)#time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=22, tm_min=3, tm_sec=20, tm_wday=3, tm_yday=1, tm_isdst=0)
print('这个两个时间点相差的时间为{}年,{}月,{}天,{}小时,{}分钟,{}秒'\
       .format(
        stime.tm_year-1970,
        stime.tm_mon-1,
        stime.tm_mday-1,
        stime.tm_hour,
        stime.tm_min,
        stime.tm_sec ,
#        stime.tm_wday,
#        stime.tm_yday,
#       stime.tm_isdst
      ))#format后面多了三项也不会报错  这个两个时间点相差的时间为0年,0月,0天,22小时,3分钟,20秒

sstime=(stime.tm_year-1970,
        stime.tm_mon-1,
        stime.tm_mday-1,
        stime.tm_hour,
        stime.tm_min,
        stime.tm_sec,
        stime.tm_wday,
        stime.tm_yday,
        stime.tm_isdst)
while True:
        fftime=time.strftime('%y/%m/%d %H:%M:%S',sstime)
        print(sstime)#不满一年,报错,不出结果,
    except:
        break

升级版
import time
def func(ftime1,ftime2,time_format='%Y-%m-%d %H:%M:%S'):#'%Y-%m-%d %H:%M:%S'
    # 和前面的ftime1='2018-5-22 11:02:50'的格式一定要保持一致。
    ttime1=time.mktime(time.strptime(ftime1,time_format))
    ttime2=time.mktime(time.strptime(ftime2, time_format))
    ttime=ttime1-ttime2
    stime=time.gmtime(ttime)
    return ('这个两个时间点相差的时间为{}年,{}月,{}天,{}小时,{}分钟,{}秒'\
           .format(
            stime.tm_year-1970,
            stime.tm_mon-1,
            stime.tm_mday-1,
            stime.tm_hour,
            stime.tm_min,
            stime.tm_sec ))
ftime1='2018-5-22 11:02:50'
ftime2='2018-5-21 12:59:30'
ret=func(ftime1,ftime2)
print(ret)#这个两个时间点相差的时间为0年,0月,0天,22小时,3分钟,20秒

random模块

import random
网业,手机上的验证码
6位/4位数字 —— 验证码
[0-9] choice 6次 正确
[0-9] sample 6个 错误 不能取到重复的数字

6位存数字验证码
s=''
for i in range(6):
    num=str(random.randint(0,9))
    s+=num
print(s)

6位带字母的验证码
s=''
for i in range(6):
    s1=str(random.randint(0,9))
    num1=random.randint(97,122)#a-z 的ASCII
    num2=random.randint(65,90)#A-Z 的ASCII
    s2=str(chr(num1))#chr(ASCII)-->字母
    s3 =str(chr(num2))
    s4=random.choice([s1,s2,s3])#随机抽取一个,[s1,s2,s3]这是个列表
    s+=s4
print(s)

os模块

import os
print(os.getcwd())#D:\untitled3\day17  执行当前所在的目录
os.chdir(r'D:\\untitled3\day17')
print(os.getcwd())#D:\untitled3\day17
print(os.curdir)#.
print(os.pardir)#..
print(os.listdir('D:\\untitled3'))#['.idea', 'day1', 'day10', 'day11', 'day12', 'day13', 'day14', 'day15', 'day16',
#  'day17', 'day2', 'day3', 'day4', 'day5', 'day6', 'day7', 'day8', 'day9', 'json_demo', 'json_demo2', 'venv', '练习.py']
print(os.stat(r'D:\\untitled3\day17\os模块.py'))#os.stat_result(st_mode=33206, st_ino=6755399441072278,
# st_dev=1290261049, st_nlink=1, st_uid=0, st_gid=0, st_size=499, st_atime=1526996670, st_mtime=1526996670, st_ctime=1526996670)
print(os.pathsep)#;

os.system('dir')
ret=os.popen('ipconfig').read()
print(ret)

os.environ['a']='bv'
print(os.environ)
pass
print(os.path.abspath('4.时间模块.py'))
print(os.path.split(r'D:\S12\py笔记\day17\4.时间模块.py'))
print(os.path.dirname(r'D:\S12\py笔记\day17\4.时间模块.py'))
print(os.path.basename(r'D:\S12\py笔记\day17\4.时间模块.py'))
print(os.path.join('D:\\S12\\py笔记\\day17','4.时间模块.py'))

print(os.path.isabs(r'D:\S12\py笔记\day17\4.时间模块.py'))
print(os.path.isfile(r'D:\S12\py笔记\day17\4.时间模块.py'))
print(os.path.isdir(r'D:\S12\py笔记\day17'))

print(os.path.getsize(r'D:\S12\py笔记\day17\4.时间模块.py'))
print(os.path.getsize(r'D:\S12\py笔记\day17')) # 4096
print(os.path.getsize(r'D:\S12\py笔记'))
pass

所有文件 与 文件夹的大小
作业 - 递归 & 循环

sys模块

import sys   # 模块
print(sys.path)  # 从哪儿导入的这个模块?
sys.path == 模块导入遵循的路径

print(sys.version)
print(sys.platform)

print(sys.argv)   #

if len(sys.argv)==3 and sys.argv[1] == 'alex' and sys.argv[2] == 'alex3714':
    print('计算器')
else:
    print('没有通过验证')
    exit()

自动化开发的程序员
    简化了交互过程
    命令行操作化

数据库 —— mysql -u username -p password
linux操作系统 ——

序列化模块

序列:有序的排列 列表 元祖 字符串 bytes
序列化
特指字符串
将普通的数据类型转换成字符串或者bytes的过程。
数据结构
容器类型
为什么要用序列化呢?
要固态的储存一个数据结构
要在网络上传输一个数据结构

列表,字典
dic={姓名:年龄,姓名:年龄,姓名:年龄,姓名:年龄}
字典->字符串->文件->字符串->字典

程序
{卡号:{
消费时间
消费金额
订单号码
}}

import json
序列化  dict--str
dic={'k':'v'}
print(dic,type(dic))#<class 'dict'>
ret=json.dumps(dic)
print(ret,type(ret))#{"k": "v"} <class 'str'>
# 反序列化str-->dict/list
res=json.loads(ret)
print(res,type(res))#{'k': 'v'} <class 'dict'>

lst=[1,2,3]
print(lst,type(lst))#[1, 2, 3] <class 'list'>
ret=json.dumps(lst)
print(ret,type(ret))#[1, 2, 3] <class 'str'>
反序列化str-->dict/list
res=json.loads(ret)
print(res,type(res))#[1, 2, 3] <class 'list'>

tup=(1,2,3) #tup
print(tup,type(tup))#(1, 2, 3) <class 'tuple'>
ret=json.dumps(tup)
print(ret,type(ret))#[1, 2, 3] <class 'str'>元祖变成列表了,元祖以列表的形式序列化
# 反序列化str-->dict/list
res=json.loads(ret)
print(res,type(res))#[1, 2, 3] <class 'list'>以列表的形式反回来了,

se={1,2,3}?
print(se,type(se))#{1, 2, 3}# <class 'set'>
ret=json.dumps(se)#报错,不能转化
print(ret,type(ret))

java,js..-->json
所有语言都通用的数据结构
数字
字符串
列表
字典
元祖和list非常像
元祖是作为列表被序列化的,所以在转回来的过程中也只能转化成列表

json
其他指定的数据类型-->str 序列化 dumps
str-->其他特定的数据类型 反序列化 loads

dic={'k':'v'}
ret=json.dumps(dic)
with open('json_demo','w') as f:
    f.write(ret)
with open('json_demo')as f:
   str_dic= f.read()
d=json.loads(str_dic)
print(d,type(d))#{'k': 'v'} <class 'dict'>

dic={'k':'v'}
with open ('json_demo1','w')as f:
    json.dump(dic,f)
with open('json_demo1')as f:
    print(json.load(f))
    # d=json.load(f)
    # print(d,type(d))#{'k': 'v'} <class 'dict'>


dumps/loads 内存中 数据类型 <--->str
dump/load 文件和内存之间 数据类型 <---> str

json的问题
{1:'v'}-->str-->{'1':'v'} json的key必须是一个字符串
有限的数据类型 数字 字符串 元祖 列表 字典
不能连续dump?

dic={'k':'v'}?
with open ('json_demo1','w')as f:
    json.dump(dic,f)
    json.dump(dic,f)
with open('json_demo1')as f:
    print(json.load(f))

三个模块

json
pickle
shelve

json --所有语言通用
pickle-- 只能在python 中使用
几乎可以处理所有的数据类型
可以连续向文件中dump 或者 load
shelve---简单,不全面

import pickle
dic={'k':'v',(1,2,3):{'a','b','c'}}
res=pickle.dumps(dic)
print(res,type(res))#b'\x80\x03}q\x00(K\x01K\x02K\x03\x87q... 序列化之后变成bytes类型了<class 'bytes'>
d=pickle.loads(res)
print(d,type(d))#{'k': 'v', (1, 2, 3): {'b', 'a', 'c'}} <class 'dict'>

dic={'k':'v',(1,2,3):{'a','b','c'}}
ret=pickle.dumps(dic)#<class 'bytes'>
with open('pickle_demo','wb')as f:#pickle.dumps(dic)出来是bytes 类型,要用'wb'模式
    f.write(ret)  #
with open('pickle_demo1','rb')as f:
    str_dic=f.read()
    d=pickle.loads(str_dic)
    print(d,type(d))

dic={'k':'v',(1,2,3):{'a','b','c'}}
with open ('pickle_demo1','wb')as f:#pickle.dumps(dic)出来是bytes 类型,要用'wb'模式
    pickle.dump(dic,f)
with open ('pickle_demo1','rb')as f:
    d=pickle.load(f)
    print(d,type(d))#{'k': 'v', (1, 2, 3): {'b', 'c', 'a'}} <class 'dict'>
    print(d[(1,2,3)])#{'b', 'c', 'a'}

dic={'k':'v',(1,2,3):{'a','b','c'}}
with open ('pickle_demo1','wb')as f:#pickle.dumps(dic)出来是bytes 类型,要用'wb'模式
    pickle.dump(dic,f)
    pickle.dump(dic, f)
    pickle.dump(dic, f)
with open ('pickle_demo1','rb')as f:
    while True:#防报错
        try:
            d=pickle.load(f)#d=pickle.load(f)多了会报错
            print(d,type(d))#{'k': 'v', (1, 2, 3): {'b', 'c', 'a'}} <class 'dict'>
            print(d[(1,2,3)])#{'b', 'c', 'a'}
        except:
            break
anser
{'k': 'v', (1, 2, 3): {'a', 'b', 'c'}} <class 'dict'>
{'a', 'b', 'c'}
{'k': 'v', (1, 2, 3): {'a', 'b', 'c'}} <class 'dict'>
{'a', 'b', 'c'}
{'k': 'v', (1, 2, 3): {'a', 'b', 'c'}} <class 'dict'>
{'a', 'b', 'c'}

import shelve?
f=shelve.open('shelve_file')
f['key']={'int':10,'float':9.5,'string':'Sanole deta'}
f.close()
f1=shelve.open('shelve_five')
existing=f1['key']#取出数据时,直接用key 获取即可
f1.close()
print(existing)

 

123




posted @ 2018-05-30 21:31  老虎死了还有狼  阅读(142)  评论(0)    收藏  举报