python笔记
库文件安装:
python -m pip install –user pyquery
[TOC]
列表
切片
1 | names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] |
追加
1 | names |
插入
1 | names |
修改
1 | names |
删除
1 | >>> del names[2] |
扩展
1 | >>> names |
拷贝
1 | >>> names |
统计
1 | >>> names |
排序&翻转
1 | >>> names |
获取下表
1 | >>> names |
元组
count
1 | 功能:统计当前元组中某元素的个数 |
index
1 | 功能:获取元素在元组中的索引值,对于重复的元素,默认获取从左起第一个元素的索引值 |
字符串操作
capitalize
1 | 功能:字符串首字母大写 |
casefold
1 | 功能: 字符串首字母小写 |
center
1 | 功能:字符串宽度填充,使用原有字符串+填充字符构成指定长度的新的字符串 |
count
1 | 功能:统计某个字符在字符串中出现的次数,或在字符串指定区间内完成上述操作 |
encode
1 | 功能:对字符串进行编码操作 |
endswith
1 | 功能:判断字符串是否以某个字符串结尾的,返回值为bool型 |
expandtabs
1 | 功能:将制表符'\t'转换成指定宽度的tab键分割,默认tabsize=8 |
find
1 | 功能:在字符串中查找指定字符串,找不到时返回-1 |
format
1 | 功能:格式化输出字符串 |
index
1 | 功能:在字符串中查找指定的字符串,找不到时直接报错 |
join()
1 | ~~~py |
isalnum
1 | 功能:检查判断字符串是否包含字母数字字符(http://www.yiibai.com/python/string_isalnum.html) |
isalpha
1 | 功能:检测字符串是否只由字母组成(http://www.runoob.com/python/att-string-isalpha.html) |
isdecimal
1 | 功能:检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。(参考:http://www.runoob.com/python/att-string-isdecimal.html) |
isdigit
1 | 功能:检测字符串是否只由数字组成。(参考:http://www.runoob.com/python/att-string-isdigit.html) |
isdentifier
1 | 功能:检测字符串是否是字母开头 |
isnumeric
1 | 功能:检测字符串是否只由数字组成。这种方法是只针对unicode对象。 |
isprintable
1 | 功能:判断字符串中所有字符是否都属于可见字符 |
isspace
1 | 功能:检测字符串是否为空格 |
istitle
1 | 功能:判断字符串是否适合当作标题(其实就是每个单词首字母大写) |
isupper
1 | 功能:判断字符串中所有字母字符是否都是大写字母 |
ljust
1 | 功能:返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。(参考:http://www.runoob.com/python/att-string-ljust.html) |
lower
1 | 功能:将所有的字母转换成小写字母 |
strip
1 | 功能:去除字符串两边的空格 |
maketrans
1 | 功能:用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 |
partition
1 | 功能:根据指定的分隔符将字符串进行分割。 |
replace
1 | 功能:把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 |
split
1 | 功能:字符串分割,默认是空格 |
字典
clear
1 | 功能:清空字典 |
copy
1 | 功能:浅拷贝 |
fromkeys
1 | 功能:用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。 |
get
1 | 功能:获取字典的value值 |
items
1 | 功能:返回可遍历的(键, 值) 元组数组 |
keys
1 | 功能:获取字典可遍历的键 |
pop
1 | 功能:删除字典中指定的键值 |
popiteam
1 | 功能:随机返回并删除字典中的一对键和值 |
setdefault
1 | 功能:查找键值,如果键不已经存在于字典中,将会添加键并将值设为默认值。 |
update
1 | 功能:把指定字典的键值更新到当前字典中 |
values
1 | 功能:获取字典的所有值 |
set集合
set创建空集合
name = set()
add
1 | 功能:增加集合元素 |
clear
1 | 功能:清空集合元素 |
copy
1 | 功能:浅拷贝 |
difference
1 | name.difference(li) |
discard
1 | 功能:移除元素 |
intersection
1 | 功能:取交集,建立新的set集合 |
isdisjoint
1 | 功能:判断没有交集,返回True,否则,返回False |
issbuset
1 | 功能:判断是否是子集 |
issuperset
1 | 功能:判断是否是父集 |
pop
1 | 功能:移除集合元素 |
remove
1 | 功能:移除指定集合元素 |
实例 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47s = set([3,5,9,10]) #创建一个数值集合
t = set("Hello") #创建一个唯一字符的集合
a = t | s # t 和 s的并集
b = t & s # t 和 s的交集
c = t – s # 求差集(项在t中,但不在s中)
d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中)
len(s)
set 的长度
x in s
测试 x 是否是 s 的成员
x not in s
测试 x 是否不是 s 的成员
s.issubset(t)
s <= t
测试是否 s 中的每一个元素都在 t 中
s.issuperset(t)
s >= t
测试是否 t 中的每一个元素都在 s 中
s.union(t)
s | t
返回一个新的 set 包含 s 和 t 中的每一个元素
s.intersection(t)
s & t
返回一个新的 set 包含 s 和 t 中的公共元素
s.difference(t)
s - t
返回一个新的 set 包含 s 中有但是 t 中没有的元素
s.symmetric_difference(t)
s ^ t
返回一个新的 set 包含 s 和 t 中不重复的元素
s.copy()
返回 set “s”的一个浅复制
文件操作
文件读取
文件读取全部
1
2
3FileRead = open("test.txt",'r')
FileRead.read() #读取文件所有内容,print(FileRead.read()函数输出文件内容
FileRead.close()文件循环读取行
1
2
3
4
5
6
7
81 FileRead = open("test.txt",'r')
2 for lines in FileRead.readlines():
3 print("lines:",lines.strip('\n'))
4 FileRead.close()
5
6 #输出结果
7 lines: Hello World
8 lines: Welcome To Beijing获取python在文件的当中的位置
1
2
3
4
51 FileRead = open("test.txt",'r')
2 print(FileRead.readline().strip('\n')) #读取第一行数据
3 print(FileRead.tell()) #获取python所在文件中的当前位置
4 print(FileRead.readline().strip('\n')) #读取第二行数据
5 FileRead.close()
写入数据到文件
文件写入操作
1
2
31 FileRead = open("test.txt",'w') #‘w’--是指文件将被写入数据,已有的数据将会被清空
2 FileRead.write('Hello Everybody!\nWelcome To China!') #被写入文件的数据,使用‘\n’可以实现换行操作
3 FileRead.close() #关闭文件句柄,每次读写文件都应该在最后面将文件关闭文件追加写入操作
1
2
31 FileRead = open("test.txt",'a') #‘a’--是指文件将被写入数据,已有的数据不会被清空,在已有数据后面追加下面要添加的数据
2 FileRead.write('Hello Everybody!\nWelcome To China!') #被写入文件的数据,使用‘\n’可以实现换行操作
3 FileRead.close() #关闭文件句柄,每次读写文件都应该在最后面将文件关闭
从现有文件中获取数据
获取文件的相关信息
使用Python中的模块,可以从现有文件中获取信息。使用“os”模块和“stat”模块可以获取文件的基本信息:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
191 #!/usr/local/env python3
2 '''
3 Author:@南非波波
4 Blog:http://www.cnblogs.com/songqingbo/
5 E-mail:qingbo.song@gmail.com
6 '''
7 import os
8 import stat
9 import time
10 FileStats = os.stat('test.txt') #获取文件的基本信息
11 FileInfo = {
12 'Size' : FileStats [ stat.ST_SIZE ], #文件大小
13 'LastModified' : time.ctime(FileStats[ stat.ST_MTIME]),
14 'LastAccessed' : time.ctime(FileStats[stat.ST_ATIME]),
15 'CreationTime' : time.ctime(FileStats[stat.ST_CTIME]),
16 'Mode' : FileStats [ stat.ST_MODE ]
17 }
18 print(FileStats) #os.stat_result(st_mode=33206, st_ino=6473924464448069, st_dev=434835, st_nlink=1, st_uid=0, st_gid=0, st_size=70, st_atime=1451980042, st_mtime=1451981189, st_ctime=1451979747)
19 print(FileInfo) #{'Size': 70, 'Mode': 33206, 'LastAccessed': 'Tue Jan 5 15:47:22 2016', 'LastModified': 'Tue Jan 5 16:06:29 2016', 'CreationTime': 'Tue Jan 5 15:42:27 2016'}使用os.path()判断文件类型
1
2
3
4
5
6
7
8
9
10
111 import os.path
2
3 FileStats = 'test.txt'
4 if os.path.isdir(FileStats): #判断文件是否是目录
5 print('Directory.')
6 elif os.path.isfile(FileStats): #判断文件是否是文件
7 print('File.')
8 elif os.path.islink(FileStats): #判断文件是否是快捷方式(链接)文件
9 print('Shortcut.')
10 elif os.path.ismount(FileStats): #判断文件是否是挂载文件
11 print('Mount point.')获取文件中的行数
1
2
3
4
5
6def Countnum(filename):
files = open(filename)
data = files.read()
files.flush()
files.close()
return data.count('\n')
python对目录的操作
创建目录
1
2import os
os.mkdir('testDir')创建多级目录
1
2import os
os.makedirs('testDir/test2/test3/test4') #os.makedirs()删除多级目录
1
2import os
os.removedirs('testDir/test2/test3/test4')删除目录
1
2import os
os.rmdir('testDir')
python对特定类型的文件进行操作
使用fnmatch模块显示’.txt’和’.exe’文件名
1
2
3
4
5
6
71 import fnmatch
2 import os
3 for FileName in os.listdir('/'):
4 if fnmatch.fnmatch(FileName,'*.txt'):
5 print(open(FileName).read())
6 elif fnmatch.fnmatch(FileName,'*.exe'):
7 print(FileName)“fnmatch”模块支持正则表达式:
1
2
3
4
5
6
7
8import fnmatch
import os
import re
FilePattern = fnmatch.translate('*.txt')
for FileName in os.listdir('./'):
if re.match(FilePattern,FileName):
print('Text file.')使用glob模块查找一种类型的文件比较方便
1
2
3
4import glob
for FileName in glob.glob('*.txt'):
print(FileName)
print('Text file.')使用数字匹配文件名
1
2
3import glob
for FileName in glob.glob ( '[0-9].txt' ):
print(Filename)
数据编组
编组一个包含数字和字符的列表:
1
2
3
4
5
6
7
8
9
10
11#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import pickle
FileHandle = open( 'PickleFile.txt','wb')
TestList = ['This',2,'is',1,'a',0,'test.']
pickle.dump(TestList,FileHandle )
FileHandle.close()拆分编组:
1
2
3
4
5
6
7
8
9
10
11#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import pickle
FileHandle = open('PickleFile.txt','rb') #注意要加'b'进行二进制读写操作,否则报错
TestList = pickle.load(FileHandle)
print(TestList)
FileHandle.close()复杂编组:
1
2
3
4
5
6import pickle
FileHandle = open('PickleFile.txt','wb')
TestList = [ 123, { 'Calories' : 190 }, 'swht', [ 1, 2, 7 ] ]
pickle.dump(TestList,FileHandle)
FileHandle.close()拆组:
1
2
3
4
5
6import pickle
FileHandle = open('PickleFile.txt','rb')
TestList = pickle.load(FileHandle)
print(TestList)
FileHandle.close()
创建虚拟文件
1
2
3
4
5
6
7
8
9
10
11#!/usr/local/env python2
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import StringIO
FileHandle = StringIO.StringIO("Let freedom ring") #创建的文件存在内存中
print(FileHandle.read()) # "Let freedom ring."
FileHandle.close()1
2
3
4
5
6
7
8
9
10
11#!/usr/local/env python2
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import cStringIO
FileHandle = cStringIO.cStringIO("Let freedom ring") #创建的文件存在内存中
print(FileHandle.read()) # "Let freedom ring."
FileHandle.close()
总结:
文件管理,是众多编程语言的程序员在编写应用程序是经常遇到的问题。幸好,和其它语言相比,Python使其出乎意料地容易。Python的标准库中提供了许多相关的模块帮助程序员解决这方面的问题,而它的面向对象的机制也简化了操作。
### zip()函数
实例代码
1
2
3
4
5
6
7
8
9
10
11
12
131 #!/usr/local/env python3
2 '''
3 Author:@南非波波
4 Blog:http://www.cnblogs.com/songqingbo/
5 E-mail:qingbo.song@gmail.com
6 '''
7 #zip()函数展示
8 x = [1,2]
9 y = [5,6]
10 xy = zip(x,y)
11 print(xy) #输出xy的值 <zip object at 0x01347A80>
12 print(type(xy)) #输出xy的类型 <class 'zip'>
13 print(dict(xy)) #输出xy转换成字典类型后的值 {1: 5, 2: 6}1
2
3
4
5
6
7
8
9
101 #!/usr/local/env python2
2 >>> x = [1,2]
3 >>> y = [5,6]
4 >>> xy = zip(x,y)
5 >>> type(xy)
6 <type 'list'>
7 >>> print xy
8 [(1, 5), (2, 6)]
9 >>> print dict(xy)
10 {1: 5, 2: 6}
函数操作
参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43形参:函数中一个变量,在函数执行前无意义,在函数调用时必须指定实际参数。
实参:实际参数用户传递给所调用的函数的一个变量,其值赋值到函数中的形式参数,然后在函数中 作为变量参与函数执行
默认参数:必须放在最后
def show(a1,a2,a3 = 5):
print(a1,a2,a3)
show("wu","ha")
#返回结果:wu ha 5
指定参数:
def show(a1,a2):
print(a1,a2)
show(a2=52,a1=8)
#返回结果:8 52
动态参数:
*arg --序列:自动转换成一个元组
def show(*arg):
print(arg,type(arg))
show(23,45,67)
#返回结果:(23, 45, 67) <class 'tuple'>
#or
l = [23,45,67]
show(*l)
#返回结果:(23, 45, 67) <class 'tuple'>
**arg --字典:自动转换成一个字典
#默认字典处理
def show(**arg):
print(arg,type(arg))
show(name1='swht',name2='shen')
#返回结果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>
#or
d = {"name1"="swht","name2"="shen"}
show(**d)
#返回结果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>
*arg,**kwarges --序列和字典
def show(*args,**kwargs):
print(args,type(args),'\n',kwargs,type(kwargs))
show(23,45,67,82,name1='swht',name2='shen')
#返回结果:(23, 45, 67, 82) <class 'tuple'>
{'name2': 'shen', 'name1': 'swht'} <class 'dict'>
注意:使用*arg,**kwarges组合参数,必须是*arg在前,**kwarges在后,否则系统报错;另外实参在输入的时候也应该是按照上述顺序。非固定参数
1
2
3
4
5
6
7
8
9
10def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式
print(name,age,args)
stu_register("Alex",22)
#输出
#Alex 22 () #后面这个()就是args,只是因为没传值,所以为空
stu_register("Jack",32,"CN","Python")
#输出
# Jack 32 ('CN', 'Python')1
2
3
4
5
6
7
8
9
10def stu_register(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式
print(name,age,args,kwargs)
stu_register("Alex",22)
#输出
#Alex 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以为空
stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")
#输出
# Jack 32 ('CN', 'Python') {'province': 'ShanDong', 'sex': 'Male'}局部变量
1
2
3
4
5
6
7
8
9
10
11name = "Alex Li"
def change_name(name):
print("before change:",name)
name = "金角大王,一个有Tesla的男人"
print("after change", name)
change_name(name)
print("在外面看看name改了么?",name)输出
1
2
3before change: Alex Li
after change 金角大王,一个有Tesla的男人
在外面看看name改了么? Alex Lilambda表达式
1
2
3
4
5
6
7
8功能:简单函数的表示方式
func = lambda a:a+1
函数名 关键字 形参:函数体
创建形式参数a,函数内容为a+1,并将结果return
测试代码:
f = lambda x:x + 1
ret = f(4)
print(ret)匿名函数
1
2
3
4
5
6
7
8#这段代码
def calc(n):
return n**n
print(calc(10))
#换成匿名函数
calc = lambda n:n**n
print(calc(10))1
2
3res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
print(i)内置函数
abs()
1
2
3
4
5功能:取绝对值
>>> abs(5)
5
>>> abs(-85)
85compile()、eval()、exec()
1
2
3
4
5
6
7
8
9
10
11
12
13
14功能:compile语句是从type类型中将str里面的语句创建成代码对象。
compile语句的目的是提供一次性的字节码编译,就不用在以后的每次调用中重新进行编译了
语法:compile( str, file, type )
eveal_code = compile('1+2','','eval')
>>>eveal_code
返回结果:<code object <module> at 0x01555D40, file "", line 1>
>>>eval(eveal_code)
返回结果:3
single_code = compile( 'print("apicloud.com")', '', 'single' )
>>> single_code
返回结果:<code object <module> at 0x01555B10, file "", line 1>
>>> exec(single_code)
返回结果:apicloud.comsuper()
功能: 用来解决多重继承问题
zip()
1
2
3
4
5
6
7
8
9功能:zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表
>>> x = [1,2,3,]
>>> y = [4,5,6,]
>>> z = [7,8,9,]
>>> xyz = zip(x,y,z)
>>> print(xyz)
<zip object at 0x00FBD968>
>>> print(list(xyz))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
更多内置函数:博客园
collection
列表生成式
1
2
3a = [i+1 for i in range(10)]
a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
闭包
内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包
1
2
3
4
5
6
7
8
9
10
11def outer():
n = 10
def inner():
print("inner:", n)
return inner
val = outer()
print(val)
val()闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域
1
2
3
4
5
6
7
8
9
10# 闭包方法
def outer(a,b):
def calc(x):
print(a*b+x)
return calc
val = outer(1,2)
print(val)
val(3)装饰器(又叫语法糖)
装饰器调用原理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
def login(func):
print("To passed!")
return func
def home(name):
print("Welcome [%s] to home page!" % name)
def tv(name):
print("Welcome [%s] to TV page!" % name)
def moive(name):
print("Welcome [%s] to Moive page!" % name)
tv = login(tv) #将tv函数的内存地址传递到login()函数中,然后将tv的内存地址返回并赋给变量tv
tv("swht") #变量调用相当于函数的调用装饰器实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
def login(func): #程序执行时返回inner函数的内存地址
def inner(*arg,**kwargs):
print("To passed!")
return func(*arg,**kwargs)
return inner
def home(name):
print("Welcome [%s] to home page!" % name)
def tv(name):
print("Welcome [%s] to TV page!" % name)
def moive(name):
print("Welcome [%s] to Moive page!" % name)
tv("swht")返回结果:
1
2
3> To passed!
> Welcome [swht] to TV page!
>迭代器
迭代器是访问集合元素的一种方式。迭代器只能往前不能往后。迭代器对象从集合的第一个集合开始访问,直到所有的元素被访问完。
优点:不需要事先准备整个迭代过程中的所有元素1
2
3
4
5
6
7
8
9
10
11
12#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
names = iter(['swht','shen','jack'])
print(names)
print(names.__next__())
print(names.__next__())
print(names.__next__())返回结果:
<list_iterator object at 0x000000000114C7B8>
swht
shen
jack
生成器
定义:generator,一个函数调用时返回一个迭代器,那这个函数就叫做生成器。
作用:yield实现函数中断,并保存函数中断时的状态。中断后,程序可以继续执行下面的代码,而且可以随时可以回头再执行之前中断的函数。
可以通过yield实现在单线程的情况下实现并发运算的效果1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
def money(num):
while num > 0:
print("取款100元!")
num -= 100
yield 100
print("你当前还有%s元" % num)
ATM = money(500)
print(type(ATM))
print(ATM.__next__())
print(ATM.__next__())
print("吃包子....")
print(ATM.__next__())
print(ATM.__next__())返回结果:
取款100元!
100
你当前还有400元
取款100元!
100
吃包子….
你当前还有300元
取款100元!
100
你当前还有200元
取款100元!
100
异步实现
yield参数可以返回参数和接收参数,使用send方法可以将值传递到生成器中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import time
def consumer(name):
print("%s 开始准备吃包子!" % name)
while True:
baozi = yield #yield可以返回一个值,也可以接收一个值
print("第[%s]波包子来了,被[%s]吃了!" % (baozi,name))
def producer(name):
c1 = consumer('swht')
c2 = consumer('shen')
c1.__next__()
c2.__next__()
print("==%s开始准备做包子!==" % name)
for i in range(10):
time.sleep(1)
print("**%s做了两个包子!**" % name)
c1.send(i) #使用send方法将值传递给yield
c2.send(i)
producer('alex')
递归
演示递归进出过程:【栈的实现: 后进先出】
1
### 常用模块
time模块
在Python中,通常有这几种方式来表示时间:
- 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
- 格式化的时间字符串(Format String)
- 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
1
2
3
4
5
6
7import time
#--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
print(time.time()) # 时间戳:1487130156.419527
print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:'2017-02-15 11:40:53'
print(time.localtime()) #本地时区的struct_time
print(time.gmtime()) #UTC时区的struct_time1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#时间加减
import datetime
# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
#
# c_time = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换
datetime模块random
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import random
print(random.random())#(0,1)----float 大于0且小于1之间的小数
print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之间的整数
print(random.randrange(1,3)) #[1,3) 大于等于1且小于3之间的整数
print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合
print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716
item=[1,3,5,7,9]
random.shuffle(item) #打乱item的顺序,相当于"洗牌"
print(item)os模块
os模块是与操作系统交互的一个接口
1
2
3
4
5
6
7
8
9
10
11
12在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。
os.path.normcase('c:/windows\\system32\\')
'c:\\windows\\system32\\'
规范化路径,如..和/
os.path.normpath('c://windows\\System32\\../Temp/')
'c:\\windows\\Temp'
a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
print(os.path.normpath(a))
/Users/jieli/test11
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16os路径处理
#方式一:推荐使用
import os
#具体应用
import os,sys
possible_topdir = os.path.normpath(os.path.join(
os.path.abspath(__file__),
os.pardir, #上一级
os.pardir,
os.pardir
))
sys.path.insert(0,possible_topdir)
#方式二:不推荐使用
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))sys模块
1
2
3
4
5
6
7> 1 sys.argv 命令行参数List,第一个元素是程序本身路径
> 2 sys.exit(n) 退出程序,正常退出时exit(0)
> 3 sys.version 获取Python解释程序的版本信息
> 4 sys.maxint 最大的Int值
> 5 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
> 6 sys.platform 返回操作系统平台名称
>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45#=========知识储备==========
#进度条的效果
[# ]
[## ]
[### ]
[#### ]
#指定宽度
print('[%-15s]' %'#')
print('[%-15s]' %'##')
print('[%-15s]' %'###')
print('[%-15s]' %'####')
#打印%
print('%s%%' %(100)) #第二个%号代表取消第一个%的特殊意义
#可传参来控制宽度
print('[%%-%ds]' %50) #[%-50s]
print(('[%%-%ds]' %50) %'#')
print(('[%%-%ds]' %50) %'##')
print(('[%%-%ds]' %50) %'###')
#=========实现打印进度条函数==========
import sys
import time
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 #每次收1024
percent=recv_size/data_size #接收的比例
progress(percent,width=70) #进度条的宽度70
打印进度条shutil模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中1
2
3
4> 1 import shutil
> 2
> 3 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
>shutil.copyfile(src, dst)
拷贝文件1
2> 1 shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
>shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变1
2> 1 shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
>shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags1
21 shutil.copystat('f1.log', 'f2.log') #目标文件必须存在
shutil.copy2(src, dst)
拷贝文件和状态信息1
2
3
41 import shutil
2
3 shutil.copy2('f1.log', 'f2.log')shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹1
2
3
41 import shutil
2
3 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件1
2
3
41 import shutil
2
3 shutil.rmtree('folder1')shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。1
2
3
41 import shutil
2
3 shutil.move('folder1', 'folder3')json&pickle模块(序列化)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import 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) #-------------------等价于json.dump(dic,f)
f.close()
#-----------------------------反序列化<br>
import json
f=open('序列化对象')
data=json.loads(f.read())# 等价于data=json.load(f)1
2
3
4
5
6
7
8
9
10
11import json
#dct="{'1':111}"#json 不认单引号
#dct=str({"1":111})#报错,因为生成的数据还是单引号:{'one': 1}
dct='{"1":"111"}'
print(json.loads(dct))
#conclusion:
# 无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads
注意点1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import pickle
dic={'name':'alvin','age':23,'sex':'male'}
print(type(dic))#<class 'dict'>
j=pickle.dumps(dic)
print(type(j))#<class 'bytes'>
f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes'
f.write(j) #-------------------等价于pickle.dump(dic,f)
f.close()
#-------------------------反序列化
import pickle
f=open('序列化对象_pickle','rb')
data=pickle.loads(f.read())# 等价于data=pickle.load(f)
print(data['age'])hashlib模块
1
2
3
4
5
6# 1、什么叫hash:hash是一种算法(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算法接受传入的内容,经过运算得到一串hash值
# 2、hash值的特点是:
#2.1 只要传入的内容一样,得到的hash值必然一样=====>要用明文传输密码文件完整性校验
#2.2 不能由hash值返解成内容=======》把密码做成hash值,不应该在网络传输明文密码
#2.3 只要使用的hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import hashlib
m=hashlib.md5()# m=hashlib.sha256()
m.update('hello'.encode('utf8'))
print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592
m.update('alvin'.encode('utf8'))
print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
m2=hashlib.md5()
m2.update('helloalvin'.encode('utf8'))
print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
'''
注意:把一段很长的数据update多次,与一次update这段长数据,得到的结果一样
但是update多次为校验大文件提供了可能。
'''1
2
3
4
5
6
7import hashlib
# ######## 256 ########
hash = hashlib.sha256('898oaFs09f'.encode('utf8'))
hash.update('alvin'.encode('utf8'))
print (hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c71
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import hashlib
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))
模拟撞库破解密码logging模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import logging
# logging.warning("user [swht] is start the systerm!")
# logging.critical("server is down!")
#创建日志
logger = logging.getLogger('[Test-Log]')
logger.setLevel(logging.DEBUG)
#创建一个控制台的handler并设置日志级别
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#创建一个文件的handler并设置日志级别
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
#创建日期格式
fomatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
#add formatter to ch and fh
ch.setFormatter(fomatter)
fh.setFormatter(fomatter)
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
#输出格式:
'''
2016-02-20 16:53:27 [Test-Log] DEBUG debug message
2016-02-20 16:53:27 [Test-Log] INFO info message
2016-02-20 16:53:27 [Test-Log] WARNING warn message
2016-02-20 16:53:27 [Test-Log] ERROR error message
2016-02-20 16:53:27 [Test-Log] CRITICAL critical message
'''
### 面向对象
详见博客: [林海峰](http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label3)
面向对象进阶
详见博客: 林海峰
socket编程
1 | #_*_coding:utf-8_*_ |
1 | #_*_coding:utf-8_*_ |
详见博客:林海峰