2022年 11月 5日

Python常用函数及常用库整理

简单整理一下一些常用函数,方便自己查阅。

目录

文件操作

文件夹/目录

文件

数据格式

链表

特殊函数

一些常用函数

常用库

tqdm进度条库

tqdm模块参数说明

 常用函数使用方法

yacs参数配置库

简介

使用方法

logging日志库

使用方法


文件操作

文件夹/目录

import os

1、os.path.exists(path) 判断一个文件/目录是否存在,只要存在相匹配的文件或目录就返回True,因此当目录与文件同名时可能报错

2、os.path.isdir(fname) 判断目录是否存在,必须是目录才返回True

3、os.makedirs(path) 多层创建目录

4、os.mkdir(path) 创建目录

5、os.rmdir(path) 删除目录,只能删除空目录

6、os.rename(原文件名,新文件名) 重命名文件或文件夹

注意:makedirs与mkdir之间最大的区别是当父目录不存在的时候os.mkdir(path)不会创建,os.makedirs(path)则会创建父目录。

文件

1、os.remove(path) 删除文件

2、os.rename(原文件名,新文件名) 重命名文件或文件夹

3、os.listdir(path) 提取目录下所有文件

4、os.path.isfile(fname) 判断文件是否存在,必须是文件才返回True

5、random.sample(file_list, n) 从file_list中随机选择n个文件–import random

6、copyfile(src_path, dst_path) 将src文件内容复制到dst文件中–from shutil import copyfile

7、copy(src_path, dst_path) 将src文件复制到dst文件夹中–from shutil import copy

8、move(src_path, dst_path) 将src文件剪切到dst文件夹—from shutil import move

9、dst=os.path.join(path,”../for_bitmain/”+img) 修改文件路径

10、str.endswith(suffix[, start[, end]]) 判断字符串是否以指定后缀结尾或指定字符串,如果以指定后缀结尾返回True,否则返回False。可选参数”start”与”end”为检索字符串的开始与结束位置。

数据格式

链表

1、len(list) 长度

2、max(list) 最大值

3、min(list) 最小值

4、del(list)/del(list[i]) 删除链表或某一个元素

5、list.append(obj) 插入元素

6、list.count(obj) 统计某个元素出现的次数

7、list.pop([index = -1]) 移除一个元素,并返回其值,默认是最后一个

8、list.sort() 排序

9、list.clear() 清除

10、list.copy() 复制

特殊函数

__init__()

        等同于类的构造器,初始化某个类的一个实例。

__del__()

        等同于类的析构函数,析构某个类的一个实例。

__call__()

        使实例能够像函数一样被调用,同时不影响实例本身的生命周期(__call__()不影响一个实例的构造和析构)。但是__call__()可以用来改变实例的内部成员的值。

  1. class X(object):
  2. def __init__(self, a, b, range):
  3. self.a = a
  4. self.b = b
  5. self.range = range
  6. def __del__(self, a, b, range):
  7. del self.a
  8. del self.b
  9. del self.range
  10. def __call__(self, a, b):
  11. self.a = a
  12. self.b = b
  13. print('__call__ with ({}, {})'.format(self.a, self.b))
  14. >>> xInstance = X(1, 2, 3)
  15. >>> xInstance(1,2)
  16. __call__ with (1, 2)
  17. >>> del X

一些常用函数

1、enumerate(sequence, [start=0])

        为可迭代的序列添加了一个计数器默认从0开始

  1. elements = ('foo', 'bar', 'baz')
  2. >>> for elem in elements:
  3. ... print elem
  4. ...
  5. foo
  6. bar
  7. baz
  8. >>> for count, elem in enumerate(elements):
  9. ... print count, elem
  10. ...
  11. 0 foo
  12. 1 bar
  13. 2 baz
  14. >>> for count, elem in enumerate(elements, 42):
  15. ... print count, elem
  16. ...
  17. 42 foo
  18. 43 bar
  19. 44 baz

 2、 ‘sep’.join(seq)

        seq:分隔符,可以为空

        seq:要连接的元素序列、字符串、元组、字典

        连接字符串数组。将字符串、元组、列表中的元素以指定的分隔符连接生成一个新的字符串。

  1. #对序列进行操作(分别使用' '与':'作为分隔符)
  2. >>> seq1 = ['hello','good','boy','doiido']
  3. >>> print(' '.join(seq1))
  4. hello good boy doiido
  5. >>> print(':'.join(seq1))
  6. hello:good:boy:doiido
  7. #对字符串进行操作
  8. >>> seq2 = "hello good boy doiido"
  9. >>> print(':'.join(seq2))
  10. h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
  11. #对元组进行操作
  12. >>> seq3 = ('hello','good','boy','doiido')
  13. >>> print(':'.join(seq3))
  14. hello:good:boy:doiido
  15. #对字典进行操作
  16. >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
  17. >>> print(':'.join(seq4))
  18. boy:good:doiido:hello

常用库

tqdm进度条库

tqdm模块参数说明

  1. class tqdm(object):
  2. """
  3. Decorate an iterable object, returning an iterator which acts exactly
  4. like the original iterable, but prints a dynamically updating
  5. progressbar every time a value is requested.
  6. """
  7. def __init__(self, iterable=None, desc=None, total=None, leave=False,
  8. file=sys.stderr, ncols=None, mininterval=0.1,
  9. maxinterval=10.0, miniters=None, ascii=None,
  10. disable=False, unit='it', unit_scale=False,
  11. dynamic_ncols=False, smoothing=0.3, nested=False,
  12. bar_format=None, initial=0, gui=False):
  • iterable: 可迭代的对象, 在手动更新时不需要进行设置
  • desc: 字符串, 左边进度条描述文字
  • total: 总的项目数
  • leave: bool值, 迭代完成后是否保留进度条
  • file: 输出指向位置, 默认是终端, 一般不需要设置
  • ncols: 调整进度条宽度, 默认是根据环境自动调节长度, 如果设置为0, 就没有进度条, 只有输出的信息
  • unit: 描述处理项目的文字, 默认是’it’, 例如: 100 it/s, 处理照片的话设置为’img’ ,则为 100 img/s
  • unit_scale: 自动根据国际标准进行项目处理速度单位的换算, 例如 100000 it/s >> 100k it/s

 常用函数使用方法

1.tqdm(iterator)

        基于迭代器运行:

  1. import time
  2. from tqdm import tqdm, trange
  3. #trange(i)是tqdm(range(i))的一种简单写法
  4. for i in trange(100):
  5. time.sleep(0.05)
  6. for i in tqdm(range(100), desc='Processing'):
  7. time.sleep(0.05)
  8. dic = ['a', 'b', 'c', 'd', 'e']
  9. pbar = tqdm(dic)
  10. for i in pbar:
  11. pbar.set_description('Processing '+i)
  12. time.sleep(0.2)
  13. 100%|██████████| 100/100 [00:06<00:00, 16.04it/s]
  14. Processing: 100%|██████████| 100/100 [00:06<00:00, 16.05it/s]
  15. Processing e: 100%|██████████| 5/5 [00:01<00:00, 4.69it/s]

        手动进行更新:

  1. import time
  2. from tqdm import tqdm
  3. with tqdm(total=200) as pbar:
  4. pbar.set_description('Processing:')
  5. # total表示总的项目, 循环的次数20*10(每次更新数目) = 200(total)
  6. for i in range(20):
  7. # 进行动作, 这里是过0.1s
  8. time.sleep(0.1)
  9. # 进行进度更新, 这里设置10个
  10. pbar.update(10)
  11. Processing:: 100%|██████████| 200/200 [00:02<00:00, 91.94it/s]

yacs参数配置库

简介

        yacs是作为一个轻量级库创建的,用于定义和管理系统配置,比如那些通常可以在为科学实验设计的软件中找到的配置。这些“配置”通常包括用于训练机器学习模型的超参数或可配置模型超参数(如卷积神经网络的深度)等概念。由于您正在进行科学研究,所以再现性是最重要的,因此您需要一种可靠的方法来序列化实验配置。

使用方法

1、初始化并赋值

  1. # my_project/config.py
  2. from yacs.config import CfgNode as CN
  3. _C = CN()
  4. _C.SYSTEM = CN()
  5. # Number of GPUS to use in the experiment
  6. _C.SYSTEM.NUM_GPUS = 8
  7. # Number of workers for doing things
  8. _C.SYSTEM.NUM_WORKERS = 4
  9. _C.TRAIN = CN()
  10. # A very important hyperparameter
  11. _C.TRAIN.HYPERPARAMETER_1 = 0.1
  12. # The all important scales for the stuff
  13. _C.TRAIN.SCALES = (2, 4, 8, 16)
  14. def get_cfg_defaults():
  15. """Get a yacs CfgNode object with default values for my_project."""
  16. # Return a clone so that the defaults will not be altered
  17. # This is for the "local variable" use pattern
  18. return _C.clone()
  19. # Alternatively, provide a way to import the defaults as
  20. # a global singleton:
  21. # cfg = _C # users can `from config import cfg`

2、解析yaml文件

        config.yaml

  1. GPUS: (0,1,2,3)
  2. OUTPUT_DIR: 'output'
  3. CUDNN:
  4. ENABLED: true
  5. MODEL:
  6. NAME: 'yolo'
  7. PRETRAINED: 'xx.pth'
  8. EXTRA:
  9. FINAL_CONV_KERNEL: 1
  10. STAGE2:
  11. NUM_MODULES: 1

        config.py

  1. import os
  2. from yacs.config import CfgNode as CN
  3. class config():
  4. def __init__(self):
  5. self.cfg = CN()
  6. self.cfg.GPUS= (0,1,2,3)
  7. self.cfg.OUTPUT_DIR= 'output'
  8. self.cfg.CUDNN=CN()
  9. self.cfg.CUDNN.ENABLED=True
  10. self.cfg.MODEL=CN()
  11. self.cfg.MODEL.NAME=''
  12. self.cfg.MODEL.PRETRAINED=''
  13. self.cfg.MODEL.EXTRA=CN()
  14. self.cfg.MODEL.EXTRA.FINAL_CONV_KERNEL=0
  15. self.cfg.MODEL.EXTRA.STAGE2=CN()
  16. self.cfg.MODEL.EXTRA.STAGE2.NUM_MODULES=0
  17. def get_cfg(self):
  18. return self.cfg.clone()
  19. def load(self,config_file):
  20. self.cfg.OUTPUT_DIR = ''
  21. self.cfg.defrost()
  22. self.cfg.merge_from_file(config_file)
  23. self.cfg.freeze()
  24. if __name__ == '__main__':
  25. cc=config()
  26. cc.load("test.yaml")
  27. print(cc.cfg)
  28. print(cc.get_defalut_cfg())

logging日志库

使用方法

1、将控制台的输出写入文件中

  1. import logging
  2. def setLog():
  3. log_file = 'L:/log/console.log'
  4. head = '%(asctime)-15s %(message)s'
  5. logging.basicConfig(filename=str(log_file), format=head)
  6. logger = logging.getLogger()
  7. logger.setLevel(logging.INFO)
  8. console = logging.StreamHandler()
  9. logging.getLogger('').addHandler(console)
  10. return logger
  11. if __name__ == '__main__':
  12. logger = setLog()
  13. logger.info('input message')