假期(模块相关)

# ----------------------------------------------------------------------------------------
import time
timestamp = time.time()    #时间戳
struct_time = time.localtime()      #结构化时间
format_time = time.strftime("%Y-%m-%d %X")   #格式化时间

# print(time.localtime(timestamp))         #  时间戳   ====== >  结构化时间
# print(time.mktime(struct_time))        #  结构化时间   ======>  时间戳

# print(time.strftime("%Y-%m-%d %X"),struct_time)     #格式化时间 ===== > 结构化时间
# print(time.strptime("2018-02-13 09:25:45","%Y-%m-%d %X"))   #结构化时间 === > 格式化时间

# print(time.asctime())              #Tue Feb 13 09:28:49 2018
# print(time.ctime(timestamp))         #Tue Feb 13 09:29:29 2018

# time.sleep(10)     #睡多少秒

# ----------------------------------------------------------------------------------------
import random

# print(random.random())     #0-1的随机小数
# print(random.randint(1,4))   # 产生大于等于1,小于等于4的整数
# print(random.randrange(1,4))    # 产生大于等于1,小于4的整数
# print(random.choice([1,"23",[4,5]]))   #随机产生列表中的一项
# print(random.sample([1,"23",[4,5],2],2))   #第一个参数是列表,第二个参数是随便产生的列表项
# print(random.uniform(1,3))     #产生1-3之间的随机小数

# item = [1,2,3,4,5,6]
# random.shuffle(item)    #打乱原列表的顺序,没有返回值
# print(item)
# 生成随机验证码
# def make_code(n):
#     res = ""
#     for i in range(n):
#         s1 = chr(random.randint(65,90))
#         s2 = str(random.randint(0,9))
#         res+=random.choice([s1,s2])
#     return res
# print(make_code(9))

# ----------------------------------------------------------------------------------------
import os
# print(os.getcwd())       #获取当前工作目录
# print(os.chdir("dirname"))  #相当于cd切换命令
# os.remove("dirname")     #删除dirname目录
# os.rename("oldname","newname")   #重命名
# print(os.environ)              #获取当前的环境变量
# os.path.join("dirname")    #路径拼接

# ----------------------------------------------------------------------------------------
import sys
# print(sys.argv)          #当前程序的路径
# print(sys.exit(0))       #退出程序
# print(sys.version)         #获取python的版、本信息
# print(sys.maxsize)         #获取最大int值
# print(sys.path)            #返回模块的搜索路径
# print(sys.platform)         #返回操作系统的名称
# 实现打印进度条
# def progress(percent,width=50):
#     if percent >= 1:
#         percent = 1
#     show_str = ('[%%-%ds]'%width)%(int(width*percent)*"#")
#     print('\r%s %d%%'%(show_str,int(100*percent)),file=sys.stdout,flush=True,end="")
# data_size = 1025
# recv_size = 0
# while recv_size < data_size:
#     time.sleep(0.1)
#     recv_size += 1024
#     percent = recv_size/data_size
#     progress(percent,width=70)

# ----------------------------------------------------------------------------------------
import shutil
# shutil.copyfile("file1","file2")     #将文件内容拷贝到另一个文中
# shutil.copymode("file1.log","file2.log")  #仅仅拷贝权限  file2.log 必须存在
# shutil.copystat("file1","file2")    #拷贝状态信息,file2必须存在
# shutil.copy("file1.log","file2.log")    #拷贝文件和权限
# shutil.copy2("file1.log","file2.log")    #拷贝文件和状态信息
# shutil.copytree()    #递归拷贝
# shutil.rmtree("filepath")   #递归删除文件
# shutil.move("file1","file2")  #递归的去移动文件

# ----------------------------------------------------------------------------------------
import json
# x = "[1,2,3,4,5,6,7,8]"
# print(x,type(x))    #[1,2,3,4,5,6,7,8] <class 'str'>
# print(eval(x),type(eval(x)))       #[1, 2, 3, 4, 5, 6, 7, 8] <class 'list'>
# print(json.loads(x),type(json.loads(x)))      #[1, 2, 3, 4, 5, 6, 7, 8] <class 'list'>
# json数据主要用于跨平台数据交互
# dic = {'name':'alvin','age':23,'sex':'male'}
# print(type(dic))       #<class 'dict'>
# j = json.dumps(dic)
# print(type(j))      # <class 'str'>

# f = open("序列化对象","w")
# f.write(j)
# f.close()
# #反序列化操作
# f = open("序列化对象","r")
# data = json.loads(f.read())
# json不认单引号,json可以跨平台交互,pickle只可以在python中数据交互
# import pickle
# dic = {'name':'alvin','age':23,'sex':'male'}
# j = pickle.dumps(dic)
# print(type(j))     #<class 'bytes'>

# ----------------------------------------------------------------------------------------
import shelve
# shelve模块比pickle模块更加的简单,只有一个open函数,返回类字典对象,可读可写,key必须为字符串,值可以是python所支持的数据类型
# f=shelve.open(r'sheve.txt')
# # f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# # f['stu2_info']={'name':'gangdan','age':53}
# # f['school_info']={'website':'http://www.pypy.org','city':'beijing'}
#
# print(f['stu1_info']['hobby'])
# f.close()
# ----------------------------------------------------------------------------------------
import xml        #这个模块以及过时,已经被lxml取代
# ----------------------------------------------------------------------------------------
import configparser
# ----------------------------------------------------------------------------------------
import hashlib
m = hashlib.md5()
m.update("hello_zhang".encode("utf8"))
print(m.hexdigest())     #ed5e024cfdceba3e24b4333709d2dc1a
#模拟撞库破解密码
passwds=[
    'alex3714',
    'alex1313',
    'alex94139413',
    'alex123456',
    '123456alex',
    'a123lex',
    ]
def make_passwd_dic(passwds):
    dic={}
    for passwd in passwds:
        m=hashlib.md5()
        m.update(passwd.encode('utf-8'))
        dic[passwd]=m.hexdigest()
    return dic

def break_code(cryptograph,passwd_dic):
    for k,v in passwd_dic.items():
        if v == cryptograph:
            print('密码是===>\033[46m%s\033[0m' %k)

cryptograph='aee949757a2e698417463d47acac93df'
break_code(cryptograph,make_passwd_dic(passwds))

# ----------------------------------------------------------------------------------------
import re
# =================================匹配模式=================================
#一对一的匹配
# 'hello'.replace(old,new)
# 'hello'.find('pattern')

#正则匹配
import re
#\w与\W
print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
print(re.findall('\W','hello egon 123')) #[' ', ' ']

#\s与\S
print(re.findall('\s','hello  egon  123')) #[' ', ' ', ' ', ' ']
print(re.findall('\S','hello  egon  123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']

#\n \t都是空,都可以被\s匹配
print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']

#\n与\t
print(re.findall(r'\n','hello egon \n123')) #['\n']
print(re.findall(r'\t','hello egon\t123')) #['\n']

#\d与\D
print(re.findall('\d','hello egon 123')) #['1', '2', '3']
print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']

#\A与\Z
print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$

#^与$
print(re.findall('^h','hello egon 123')) #['h']
print(re.findall('3$','hello egon 123')) #['3']

# 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
#.
print(re.findall('a.b','a1b')) #['a1b']
print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b','a\nb')) #[]
print(re.findall('a.b','a\nb',re.S)) #['a\nb']
print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样

#*
print(re.findall('ab*','bbbbbbb')) #[]
print(re.findall('ab*','a')) #['a']
print(re.findall('ab*','abbbb')) #['abbbb']

#?
print(re.findall('ab?','a')) #['a']
print(re.findall('ab?','abbb')) #['ab']
#匹配所有包含小数在内的数字
print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']

#.*默认为贪婪匹配
print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']

#.*?为非贪婪匹配:推荐使用
print(re.findall('a.*?b','a1b22222222b')) #['a1b']

#+
print(re.findall('ab+','a')) #[]
print(re.findall('ab+','abbb')) #['abbb']

#{n,m}
print(re.findall('ab{2}','abbb')) #['abb']
print(re.findall('ab{2,4}','abbb')) #['abb']
print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'

#[]
print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']

#\# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c']

#():分组
print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容

#|
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))



# ===========================re模块提供的方法介绍===========================
import re
#1
print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
#2
print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。

#3
print(re.match('e','alex make love'))    #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match

#4
print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割

#5
print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有
print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex

print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数


#6
obj=re.compile('\d{2}')

print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj

 

posted @ 2018-02-13 16:45  前方、有光  阅读(212)  评论(0编辑  收藏  举报