zoukankan      html  css  js  c++  java
  • python常用库

    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个时间点相差了多少个小时:

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

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

    datetime.datetime.now() +  datetime.timedetla(3) # 当前时间+3天
    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的序列打乱

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

    import random 
    checkcode = ''   # 4位数字
    for i in range(4):
        current = random.randint(1,9)
        checkcode += str(current)
    print(checkcode)
    
    checkcode = ''   # 4位数字或大写字母
    for i in range(4):
        current = random.randint(0,3)
        if current == i:
            tmp = chr(random.randint(65, 90))
        else:
            tmp = random.randint(0, 9)
        checkcode += str(tmp)
    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:acd')
    • 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下为" ",Linux下为" "
    • 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 ')

    终止程序并显示错误:

    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

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

    方法二:json

    # dumps序列化:
    f.write(json.dumps(info))
    json.dump(info, f) 
    # loads反序列化:       
    json.loads(f.read())   
    json.load(f)

    方法三:pickle,参照json

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

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

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

    7,paramiko

    SSH登录

    9,itertools

    9.1,过滤

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

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

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

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

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

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

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

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

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

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

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

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

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

    9.2,映射

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

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

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

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

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

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

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

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

      

    9.3,容器合并

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

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

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

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

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

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

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

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

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

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

      

    9.4,输入—>输出n

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

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

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

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

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

    >>> list(itertools.permutations('abc', 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是分组标准,使用前必须先根据分组标准排序

    # 根据首字母分组:
    l = ['apple', 'dark', 'china', 'apache', 'cry', 'department','cycle']
    l.sort(key=lambda i: i[0])   # 必须先排序
    for first_letter, group in itertools.groupby(l, key=lambda i: i[0]):
        print(first_letter, list(group))
    # 输出为:
    a ['apple', 'apache']
    c ['china', 'cry', 'cycle']
    d ['dark', 'department']
    
    # 根据单词字母数量分组:
    l = ['apple', 'dark', 'china', 'apache', 'crazy', 'depart', 'cycle']
    l.sort(key=len)   # 必须先排序
    for first_letter, group in itertools.groupby(l, key=len):
        print(first_letter, list(group))
    # 输出为:
    4 ['dark']
    5 ['apple', 'china', 'crazy', 'cycle']
    6 ['apache', 'depart'
    
    # 字典列表中,根据根据x的value的首字母进行分组:
    rows = [{'x': 'apple', 'y': 'a'},    
            {'x': 'dark', 'y': 'b'},
            {'x': 'china', 'y': 'a'},
            {'x': 'apache', 'y': 'a'},
            {'x': 'cry', 'y': 'c'},
            {'x': 'department', 'y': 'a'},
            {'x': 'cycle', 'y': 'b'}]
    rows.sort(key=itemgetter('x'))
    for i, t in groupby(rows, key=lambda i: itemgetter('x')(i)[0]):
        print(i)
        for j in t:
            print(j)
    # 输出为:
    a
    {'x': 'apache', 'y': 'a'}
    {'x': 'apple', 'y': 'a'}
    c
    {'x': 'china', 'y': 'a'}
    {'x': 'cry', 'y': 'c'}
    {'x': 'cycle', 'y': 'b'}
    d
    {'x': 'dark', 'y': 'b'}
    {'x': 'department', 'y': 'a'}
    

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

    >>> t = itertools.tee(iter(range(5)), 2)
    >>> list(t[0])
    [0, 1, 2, 3, 4]
    >>> list(t[1])
    [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:一键多值字典

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

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

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

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

    collections.namedtuple():具名元组

    Stock = namedtuple('Stock', 'name shares price')
    s = Stock('IBM', 1000, 70)
    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()的区别

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

    12,operator

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

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

    attrgetter:获取对象的属性

    class User:
        def __init__(self, user_id):
            self.user_id = user_id
        def __repr__(self):
            return 'User({})'.format(self.user_id)
    users = [User(3), User(10), User(7)]
    # attrgetter用法示例:attrgetter返回的是一个函数,需要作用到类的实例上
    key = attrgetter('user_id')
    for u in users:
        print(key(u), end=' ')  # 3 10 7 
    # 方法一:attrgetter
    users.sort(key=attrgetter('user_id'))
    # 方法二:lambda
    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

    >>>fnmatch.fnmatch('test.py', '*.py')
    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') :获取文件

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

      

    15,functools

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

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

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

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

    16,io

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

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

    17,mmap

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

    def memory_map(filename, access=mmap.ACCESS_WRITE):
        size = os.path.getsize(filename)
        fd = os.open(filename, os.O_RDWR)
        return mmap.mmap(fd, size, access=access)
    
    with open('data', 'wb') as f:
        f.seek(999999)
        f.write(b'x00')
    
    m = memory_map('data')
    print(len(m))      # 1000000
    print(m[0: 11])   # b'x00x00x00x00x00x00x00x00x00x00x00'
    m[0: 11] = b'hello world'
    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()  # 从配置文件中进行配置
  • 相关阅读:
    docker安装与使用路径
    python3.7简单的爬虫
    ubuntu19.04下查看软件安装目录和详细信息
    Javascript检查对象是否存在某个属性
    bootstrap源码和测试
    python学习笔记之pdb调试
    pydensecrf安装报错1、UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 29: invalid start byte2、 LINK : fatal error LNK1158: 无法运行“rc.exe” error: command 'D:\software\vs2015\VC\BIN
    python学习日记:np.newaxis
    好用的网址集锦
    网络配置ipconfig /release、ipconfig /renew
  • 原文地址:https://www.cnblogs.com/guxh/p/10273846.html
Copyright © 2011-2022 走看看