当前位置:   article > 正文

python常用库

numpy dirac

1,time

时间的表示形式:

  • 格式化的字符串:'2018-2-4 14:08:01'
  • 时间戳:1970年1月1日至今经历的秒数
  • 元组(struct_time):time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=10, tm_min=34, tm_sec=56, tm_wday=6, tm_yday=35, tm_isdst=0

 

time模块方法:

  • time():获取本地时间戳
  • gmtime(secondes):UTC时间戳 —> 元组,缺省为当前时间
  • localtime(seconds):本地时间戳 —> 元组,缺省为当前时间
  • mktime(tupple):元组 —> 时间戳
  • strftime(format[,tupple]):元组 —> 字符串,例如time.strftime("%Y-%m-%d %H-%M-%S") ,不输入tupple是本地时间
  • strptime(string, format):字符串 —> 元组,例如time.strptime(%H-%M-%S", "%Y-%m-%d"),不输入tupple是本地时间
  • asctime([tupple]):元组 —> 字符串,是sat aug 20 15:01:42 2016这种格式
  • ctime(seconds):时间戳 —> 字符串,是sat aug 20 15:01:42 2016这种格式
  • sleep():略

 

举例,改时间戳,计算2个时间点相差了多少个小时:

  1. def timeformat(item): # 改时间戳
  2. local_timeArray = time.strptime(item, "%Y-%m-%d %H:%M:%S")
  3. local_timeStamp = int(time.mktime(local_timeArray))
  4. return round(float(local_timeStamp)/3600, 2) # 对时间戳换算到小时并保留2位
  5. >>> t1 = timeformat('2019-3-27 18:20:01')
  6. >>> t1
  7. 431578.33
  8. >>> t2 = timeformat('2019-3-29 6:10:20')
  9. >>> t2
  10. 431614.17
  11. >>> t2 - t1
  12. 35.839999999967404 # t2减去t1,相差35.84个小时

 

datatime:time的高级封装,包括date类,time类,datetime类

  1. datetime.datetime.now() +  datetime.timedetla(3) # 当前时间+3天
  2. datetime.datetime.now() +  datetime.timedetla(hours=3# 当前时间+3个小时

 

2,random

  • random.random() # 0到1之间的随机浮点数
  • random.uniform(1, 10)  # 1到10之间的随机浮点数,相比较random增加了区间功能
  • random.randint(1, 8)  # 1到8之间的随机整数,范围是[1,8],包括1和8
  • random.randrange(1,8) # 1到8之间的随机整数,范围是[1,7],包括1,但不包括8,和range一样,顾头不顾尾
  • random.choice('hello')  # 从传入的序列中随机取值,可以传字符串、列表元组等
  • random.sample('hello', 2)  # 从传入的序列中随机取2个值
  • random.shuffle(list)  # 把传入的list的序列打乱

举例,生成伪随机验证码:

  1. import random
  2. checkcode = '' # 4位数字
  3. for i in range(4):
  4.     current = random.randint(1,9)
  5.     checkcode += str(current)
  6. print(checkcode)
  7. checkcode = '' # 4位数字或大写字母
  8. for i in range(4):
  9.     current = random.randint(0,3)
  10.     if current == i:
  11.         tmp = chr(random.randint(65, 90))
  12.     else:
  13.         tmp = random.randint(0, 9)
  14.     checkcode += str(tmp)
  15. print(checkcode)

  

3,os

  • os.getcwd()     # 获取当前工作目录
  • os.listdir(path)    # 列出指定目录下的所有文件和f子目录,包括隐藏文件。listdir不会遍历子目录,但os.walk会遍历子目录。
>>> os.listdir(os.getcwd())  # 获取执行脚本所在文件下的全部内容
  • os.walk(path)  # 遍历目录,返回generator,三元组:当前路径,当前路径下的文件夹列表,当前路径下的文件列表
  • os.chdir("dirname")   # 改变当前脚本工作目录;相当于shell下cd,注意切换目录时需要转移,方法一用'/',方法二前面加'r'
  • os.curdir  # 返回当前目录: ('.')
  • os.pardir  # 获取当前目录的父目录字符串名:('..')
  • os.mkdir('dirname')    # 生成单级目录;相当于shell中mkdir dirname
  • os.makedirs('dirname1/dirname2')    # 可生成多层递归目录,例如:os.mkdirs(r'd:\a\b\c\d')
  • os.rmdir('dirname')    # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname,清理单个空文件夹
  • os.removedirs('dirname1')    # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推,清理递归空文件夹
  • os.remove()  # 删除一个文件
  • os.rename("oldname","newname")  # 重命名文件/目录
  • os.stat('path/filename')  # 获取文件/目录信息,atime存储时间,mtime修改时间,大小等等
  • os.sep    # 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
  • os.linesep    # 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
  • os.pathsep    # 输出用于分割文件路径的字符串
  • os.name    # 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
  • os.system("bash command")  # 运行linux的shell命令,windows的cmd命令
  • os.environ  # 获取系统环境变量,返回的是所有环境变量,sys.path返回的是python相关的环境变量
  • os.get_terminal_size()  # 获取终端大小

 

os.path

  • os.path.dirname(pah):返回path的目录名
  • os.path.basename(path):返回path的文件名
  • os.path.split(path):返回路径 + 文件/文件名
  • os.path.splitext(path):返回路径 + 后缀
  • os.path.exists(path):是否存在
  • os.path.isfile(path):是否文件
  • os.path.isdir(path):是否目录
  • os.path.islink(path):是否link
  • os.path.isabs(path):是否绝对路径
  • os.path.realpath(path):link对应的真实路径
  • os.path.listdir(path):获取path下的目录 + 文件列表
  • os.path.abspath(path) :返回path规范化的绝对路径
  • os.path.join(path1[, path2[, ...]]):将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
  • os.path.size(path):获取大小
  • os.path.getmtime(path):最后修改时间
  • os.path.getatime(path):最后存取时间

 

4,sys

  • sys.argv   # 是传给脚本的参数,是一个list,python abc.py 1 2 3,sys.argv就是[abc.py, 1, 2, 3]
  • sys.exit(n)  # 退出程序,正常退出时exit(0)
  • sys.version    # 获取Python解释程序的版本信息
  • sys.maxint    # 最大的Int值
  • sys.path   # 返回模块的绝对路径,初始化时使用PYTHONPATH环境变量的值
  • sys.platform   # 返回操作系统平台名称
  • sys.stdout.write() 和 sys.stdout.flush()   # print('abc') 等效于 sys.stdout.write('abc\n')

终止程序并显示错误:

raise SystemExit('it falied') 

 

5,shutil

copy文件,压缩文件、拷贝目录、删除目录等,shutil压缩功能是通过调用zipfile和tarfile这2个模块实现的

  • shutil.copyfileobj(src, dst)  # 需要自己open
  • shutil.copyfile(src, dst)  # 无需自己open,只拷贝文件
  • shutil.copy(src, dst)  # 同时拷贝文件和权限
  • shutil.copy2(src, dst)  # 拷贝文件保留元数据
  • shutil.copytree(src, dst)  # 拷贝目录,如果想保留符号链接,可以设置Symlinks=True
  • shutil.move(src, dst)  # 移动文件
  • shutil.copymode 
  • shutil.copystat  # 拷贝状态信息
  • shutil.make_archive()  # 压缩
  • shutil.unpack_archive()  # 解压缩

 

6,json,pickle,shelve,PyYAML,ConfigParser,xml.etree.ElementTree

处理json,序列化,反序列化,配置文件

常见配置文件:

适合人类编写:ini > toml > yaml > json > xml > plist

可以存储的数据复杂度:xml > yaml > toml ~ json ~ plist > ini

json:所有语言之间交互,但只能传字典

pickle:python内部交互,可以传所有内容

shelve:pickle更上一层封装

PyYAML:处理yaml配置文件

ConfigParser:处理ini配置文件

xml.etree.ElementTree:处理xml文件

 

序列化举例,字典到文件的读写:

方法一:str + eval

  1. f.write(str(dict)) # 转成str存,即序列化
  2. eval(str(dict))  # 用eval读,即反序列化

方法二:json

  1. # dumps序列化:
  2. f.write(json.dumps(info))
  3. json.dump(info, f)
  4. # loads反序列化:
  5. json.loads(f.read())
  6. json.load(f)

方法三:pickle,参照json

json不支持函数序列化,pickle支持函数的序列化

json可以跨语言,pickle只能python内部

注意:json和pickle,python3只能dump和load一次

 

7,paramiko

SSH登录

 

9,itertools

9.1,过滤

  1. def screen(val):
  2. return True if val > 0 else False
  3. ls = [3, 1, -5, 2, 3, -9, 10]

filter(fun, it): 将it中的元素i逐个传给fun,如果fun(i)为真值,name产出对应的i。

  1. >>> list(filter(screen, ls))
  2. [3, 1, 2, 3, 10]

itertools.filterfalse(fun, it):与filter功能相反

  1. >>> list(itertools.filterfalse(screen, ls))
  2. [-5, -9]

itertools.compress(it,  it_ref):并行迭代it和it_ref,如果it_ref中的值为真值,产出it中对应的值,返回的是iterable

  1. >>> list(itertools.compress('abcd', [1, 0, 1, 0]))
  2. ['a', 'c']

itertools.dropwhile(fun, it):跳过开头几个匹配为True的,后面不再匹配

  1. list(itertools.dropwhile(screen, ls))
  2. [-5, 2, 3, -9, 10] # 后面再碰到返回True的2不再跳过了

itertools.takewhile(fun, it):产出相当于dropwhile丢掉的几个值,takewhile + dropwhile = it

  1. >>> list(itertools.takewhile(screen, ls))
  2. [3, 1]

itertools.islice(it, start, stop, step):切片,it可以是任何iterable,start可选默认=0,step可选默认=1,注意:迭代器由于没有getitem没法使用普通切片函数,islice会消耗掉迭代器中的数据。如果stop=None,表示无限大,结合start值可以用来跳过前几个元素。

  1. def count(n):
  2. while True:
  3. yield n
  4. n += 1
  5. c = count(1)
  6. >>> list(itertools.islice(c, 10, 20, 2))
  7. [11, 13, 15, 17, 19]
  8. >>> list(itertools.islice(c, 10, 15))
  9. [11, 12, 13, 14, 15]
  10. >>> list(itertools.islice(c, 5))
  11. [1, 2, 3, 4, 5]

 

9.2,映射

enumerate(it, start=0) :索引 + value

  1. >>> list(enumerate('abcde', 1))
  2. [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

map(fun, it1[it2, it3, ... itN]):将it中的元素传给fun,产出元素

  1. >>> list(map(lambda x, y: x + y, [1, 2, 3], [1, 1, 1]))
  2. [2, 3, 4]  

itertools.accumulate(it, [fun]):产出列表,不断将it传给后面的函数,产出结果,如果没有函数,产出累加

  1. >>> list(itertools.accumulate([1, 3, 2, 4]))
  2. [1, 4, 6, 10]
  3. >>> list(itertools.accumulate([1, 3, 2, 4], operator.mul))
  4. [1, 3, 6, 24]

itertools.startmap(fun, it):获取it中的元素,传给fun执行

  1. >>> list(itertools.starmap(operator.mul, enumerate('abcde', 1)))
  2. ['a', 'bb', 'ccc', 'dddd', 'eeeee']

  

9.3,容器合并

zip(it1, it2, ..., itN):从多个可迭代对象中获取元素

  1. >>> list(zip('abc', range(4)))
  2. [('a', 0), ('b', 1), ('c', 2)]

itertools.zip_longst(it1, ...itN, fillvalue=None):zip的longst版

  1. >>> list(itertools.zip_longest('abc', range(4), fillvalue='#'))
  2. [('a', 0), ('b', 1), ('c', 2), ('#', 3)]

itertools.product(it1, ...itN, repeat=1):计算笛卡尔积,矩阵展开,可以多个省略for循环语句

  1. >>> list(itertools.product('abc', range(2), repeat=1))
  2. [('a', 0), ('a', 1), ('b', 0), ('b', 1), ('c', 0), ('c', 1)]

itertools.chain(it1, it2,..., itN):依次迭代多个容器,可以是不同类型的容器,省空间不会产生新序列。heapq.merge()也可以迭代多个不同容器,但元素需要相同类型。

  1. >>> list(itertools.chain('abc', range(2), ('c', 'd'))
  2. ['a', 'b', 'c', 0, 1, 'c', 'd']

itertools.chain.from_iterable(it) : 和chain差不多, 从嵌套的容器中获取元素,只是将不同容器放在一个iterable中

  1. >>> list(itertools.chain.from_iterable(['abc', range(2), ('c', 'd')]))
  2. ['a', 'b', 'c', 0, 1, 'c', 'd']

  

9.4,输入—>输出n

itertools.combinations(it, n):前n元素的组合,不重复

  1. >>> list(itertools.combinations('abc', 2))
  2. [('a', 'b'), ('a', 'c'), ('b', 'c')]

itertools.combinations_with_replacement(it, n):前n元素的组合,可重复

  1. >>> list(itertools.combinations_with_replacement('abc', 2))
  2. [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')]

itertools.permutations(it, n=None):前n元素的排列

  1. >>> list(itertools.permutations('abc', 2))
  2. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

itertools.count(start=0, step=1):无限产出值,默认从0开始,步长为1

itertools.repeat(item, [n]):产出n次item,不提供参数n则无限产出

itertools.cycle(it):从it中无限循环产出值

 

9.5,重排

reversed(seq):反向遍历

itertools.groupby(it, key=None):分组产出iterable,key是分组标准,使用前必须先根据分组标准排序

  1. # 根据首字母分组:
  2. l = ['apple', 'dark', 'china', 'apache', 'cry', 'department','cycle']
  3. l.sort(key=lambda i: i[0]) # 必须先排序
  4. for first_letter, group in itertools.groupby(l, key=lambda i: i[0]):
  5. print(first_letter, list(group))
  6. # 输出为:
  7. a ['apple', 'apache']
  8. c ['china', 'cry', 'cycle']
  9. d ['dark', 'department']
  1. # 根据单词字母数量分组:
  2. l = ['apple', 'dark', 'china', 'apache', 'crazy', 'depart', 'cycle']
  3. l.sort(key=len) # 必须先排序
  4. for first_letter, group in itertools.groupby(l, key=len):
  5. print(first_letter, list(group))
  6. # 输出为:
  7. 4 ['dark']
  8. 5 ['apple', 'china', 'crazy', 'cycle']
  9. 6 ['apache', 'depart'
  1. # 字典列表中,根据根据x的value的首字母进行分组:
  2. rows = [{'x': 'apple', 'y': 'a'},
  3. {'x': 'dark', 'y': 'b'},
  4. {'x': 'china', 'y': 'a'},
  5. {'x': 'apache', 'y': 'a'},
  6. {'x': 'cry', 'y': 'c'},
  7. {'x': 'department', 'y': 'a'},
  8. {'x': 'cycle', 'y': 'b'}]
  9. rows.sort(key=itemgetter('x'))
  10. for i, t in groupby(rows, key=lambda i: itemgetter('x')(i)[0]):
  11. print(i)
  12. for j in t:
  13. print(j)
  14. # 输出为:
  15. a
  16. {'x': 'apache', 'y': 'a'}
  17. {'x': 'apple', 'y': 'a'}
  18. c
  19. {'x': 'china', 'y': 'a'}
  20. {'x': 'cry', 'y': 'c'}
  21. {'x': 'cycle', 'y': 'b'}
  22. d
  23. {'x': 'dark', 'y': 'b'}
  24. {'x': 'department', 'y': 'a'}

 

itertools.tee(it, n=2):产出n个相同的it

  1. >>> t = itertools.tee(iter(range(5)), 2)
  2. >>> list(t[0])
  3. [0, 1, 2, 3, 4]
  4. >>> list(t[1])
  5. [0, 1, 2, 3, 4]

 

10,collections

collections的所有方法:['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserString', 'Counter', 'OrderedDict', 'ChainMap'],详见collections/__init__.py

collections.abc:抽象基类,详见抽象基类笔记

collections.deque(maxlen=n):只保留有限的n个数据

collections.defaultdict:一键多值字典

  1. d = defaultdict(list)
  2. d['a'].append(1)

collections.OrderedDict:有序字典,类似pd.Series

collections.Counter:统计序列元素出现次数,并且Counter类对运算符进行了重载,支持统计结果加减,pandas

  1. s1 = list('imabigbiggirl')
  2. s2 = list('inabigbigworld')
  3. c1 = Counter(s1)
  4. c2 = Counter(s2)
  5. print(c1) # Counter({'i': 4, 'g': 3, 'b': 2, 'm': 1, 'a': 1, 'r': 1, 'l': 1})
  6. print(c1.most_common(3)) # [('i', 4), ('g', 3), ('b', 2)]
  7. print(c1 + c2) # Counter({'i': 7, 'g': 5, 'b': 4, 'a': 2, 'r': 2, 'l': 2, 'm': 1, 'n': 1, 'w': 1, 'o': 1, 'd': 1})
  8. pd.Series(s1).value_counts()[:3] # pandas.Series也可以完成统计前3的功能,但是2个Seires没法完成相加统计,NaN的加上int还是NaN

collections.namedtuple():具名元组

  1. Stock = namedtuple('Stock', 'name shares price')
  2. s = Stock('IBM', 1000, 70)
  3. print(s) # Stock(name='IBM', shares=1000, price=70)

collections.chinamap(m1, m2, ... mn):将多个映射合并为一个,有重复key时只取第一个,有修改映射时只作用第一个

 

11,heapq

heapq.nlargest(it, n):在it中找出最大的n个数

heapq.nsmallest(it, n):在it中找出最小的n个数

heapq.merge(it1, it2, ..., itn):对不同类型的容器进行排序后依次迭代,注意与itertools.chain()的区别

  1. >>> list(heapq.merge([1, 3, 5], (2, 4, 6)))
  2. [1, 2, 3, 4, 5, 6]

 

12,operator

itemgetter:获取字典的value,对字典列表排序,也可以用lambada,或者将字典列表交个dataframe排序,但itemgetter效果高

  1. ds = [{'a': 6, 'b': 2}, {'a': 3, 'b': 5}, {'a': 2, 'b': 7}, {'a': 4, 'b': 3}]
  2. # itemgetter用法示例:itemgetter返回的是一个函数,需要作用到参数上
  3. key = itemgetter('a')
  4. for each_dict in ds:
  5.   print(key(each_dict), end=' ') # 6 3 2 4
  6. # 方法一:itemgetter
  7. ds.sort(key=itemgetter('a')) # 根据a的value排序
  8. ds.sort(key=itemgetter('b')) # 根据b的value排序
  9. # 方法二:lambda
  10. ds.sort(key=lambda k: k['a'])
  11. # 方法三:pandas
  12. df = pd.DataFrame(ds) # 方法三:pandas,dataframe可以接收字典列表
  13. df = df.sort_values('a') # 根据'a'列排序,sort_values不会就地修改

attrgetter:获取对象的属性

  1. class User:
  2. def __init__(self, user_id):
  3. self.user_id = user_id
  4. def __repr__(self):
  5. return 'User({})'.format(self.user_id)
  6. users = [User(3), User(10), User(7)]
  7. # attrgetter用法示例:attrgetter返回的是一个函数,需要作用到类的实例上
  8. key = attrgetter('user_id')
  9. for u in users:
  10. print(key(u), end=' ') # 3 10 7
  11. # 方法一:attrgetter
  12. users.sort(key=attrgetter('user_id'))
  13. # 方法二:lambda
  14. users.sort(key=lambda u: u.user_id)

methodcaller:实现getattr的功能

operator.methodcaller('distance', 0, 0)(p)  # 相当于p.distance(0, 0)

 

13,fnmatch

fnmatch.fnmatch(filename, pattern):测试文件名是否符合pattern

  1. >>>fnmatch.fnmatch('test.py', '*.py')
  2. True

fnmatch.fnmatchcase(filename, pattern):测试文件名是否符合pattern,严格区分大小写

fnmatch.filter(filenames, pattern):对文件名列表应用pattern过滤,返回的是列表,可以用下面语句替代:

[file for file in filenames if re.match(pattern, file)]

fnmatch.translate(pattern):fnmatch将这种全局模式转换成一个正则式?

 

14,glob

glob('dir/pattern') :获取文件

  1. glob.glob('*.py') # 获取当前目录下的.py文件
  2. glob.glob('fw*.py') # 获取当前目录下含有fw的.py文件
  3. glob.glob('somedir/*.py') # 获取somedir目录下的.py文件

  

15,functools

functools.partial(fun, args): 冻结参数(好像只能冻结最后一个)

  1. def run(a, b):
  2. print(a, b)
  3. p = functools.partial(run, b='b')

functools.partial + iter:实现对固定大小内容进行迭代,f.read()可以通过partial绑定一个固定大小的参数

  1. with open('file.data', 'rb') as f:
  2. records = iter(partial(f.read, 32), b'') # 固定大小间隔为32,哨符值为‘’
  3. for i in records:
  4. ......

 

16,io

io.StringIO():类似文本文件的对象,主要有read/write/getvalue方法

io.BytesIO():类似二进制文件的对象,主要有read/write/getvalue方法

 

17,mmap

看起来就像bytearray,对文件进行内存映射不会将整个文件读到内存中,而是保留一段虚拟内存,按需映射到内存中

  1. def memory_map(filename, access=mmap.ACCESS_WRITE):
  2. size = os.path.getsize(filename)
  3. fd = os.open(filename, os.O_RDWR)
  4. return mmap.mmap(fd, size, access=access)
  5. with open('data', 'wb') as f:
  6. f.seek(999999)
  7. f.write(b'\x00')
  8. m = memory_map('data')
  9. print(len(m)) # 1000000
  10. print(m[0: 11]) # b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  11. m[0: 11] = b'hello world'
  12. print(m[0: 11]) # b'hello world'

 

18,getpass

  • getpass.getuser()  # 获取当前shell环境的用户名
  • getpass.getpass()  # 输入密码时不显示

 

19,subprocess

  • subprocess.check_out()  # 执行外部命令并获取输出
  • subprocess.Popen()  # 需要与子进程交互时

 

20,logging

  • logging.getLogger()  # 日志对象
  • logging.bascConfig()  # 设置配置信息,只能被调用一次,想修改需要通过日志对象
  • logging.config.fileConfig()  # 从配置文件中进行配置

 

转载于:https://www.cnblogs.com/guxh/p/10273846.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/66486
推荐阅读
相关标签
  

闽ICP备14008679号