Lazy loaded image
🐍Python 教程
二、内置模块和常用库
Words 4993Read Time 13 min
2024-11-29
type
date
slug
category
icon
password

1. Extended Python Knowledge

Python OS
Built-in Functions
https://www.runoob.com/python/python-built-in-functions.html
enumerate()
  • Traverse each element in the data set (list, tuples and strings) simultaneously, the index of data will be given.
  • enumerate(sequence, [start=0])
  • applicable for the "for" loop structure
hash()
  • acquire hash value of object
id()
  • return address in the memory
import()
  • Load classes or functions dynamicly
map()
  • 序列调用对象,并返回函数值序列,列表
  • map(function, iterable, ...)
  • 当func函数时None时,这就同zip()函数了,并且zip()开始取代这个了,目的是将多个列表相同位置的元素归并到一个元组。
  • 将数据转化成为列表
List index()

2. Pythonic

Error handle and operation indicatior

1. 利用tqdm模块实现进度条
最主要的用法有3种,自动控制、手动控制或者用于脚本或命令行。
2. Assert 功能
Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。
断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况,例如我们的代码只能在 Linux 系统下运行,可以先判断当前系统是否符合条件
3. 执行超时后跳过
python函数执行超时后跳过_果冻先生的专栏-CSDN博客_python 超时跳过
最近写bug时遇到一个关于函数执行超时的问题,就是某一步执行时间过长,或者程序直接卡死了,找到了三种解决方法,现在叙述下,帮助需要的人。 (1)使用eventlet 参考链接: https://blog.csdn.net/zjshui/article/details/78874621 import time import eventlet #导入eventlet这个模块 eventlet.monkey_patch() #必须加这条代码 with eventlet.Timeout(2,False): #设置超时时间为2秒 print '这条语句正常执行' time.sleep(4) print '没有跳过这条输出' print '跳过了输出' 使用eventlet的好处是在于可以真对某一步的进行限制,尤其是在写爬虫的时候有很大的益处。 但是eventlet也存在一定的问题,就是针对子进程无法跳出。如下面这个代码就有问题。 import time import eventlet import os eventlet.monkey_patch() #必须加这条代码 with eventlet.Timeout(20,False): #设置超时时间为20秒 print '这条语句正常执行' cmd1 = 'binwalk -B {0}'.format(filename) info1_lines = os.popen(cmd1).readlines() cmd2 = 'file {0}'.format(filename) info2_lines = os.popen(cmd2).readlines() print '没有跳过这条输出' print '跳过了输出' 我的目的是防止程序卡死,所以加了eventlet,但是在我使用的时候还是存在卡死的情况,当时就很郁闷,不是已经加了时间限制吗,为什么还是不能够跳出。然后发现问题出在了os模块,一直卡在此步,不能够跳出,调用了子进程。 (2)使用signal设置装饰器 参考链接: https://www.cnblogs.com/buxizhizhoum/p/7113355.html https://www.jb51.net/article/159375.htm https://www.cnblogs.com/lyxdw/p/10033118.html 废话不多说,上代码,看下代码就很请出了,比说得更清楚。 import signal def time_limit(set_time,callback): '''set_time是设置的时间限制,callback是程序运行后执行的函数''' def wraps(func): # 收到信号SIGALRM后的回调函数,参数1是信号的数字,参数2是the interrupted stack frame.
python函数执行超时后跳过_果冻先生的专栏-CSDN博客_python 超时跳过

3. Library Classification

Introduciton

python libraries for machine learning
NumPy :主要用来做一些科学运算,主要是矩阵的运算。NumPy为Python带来了真正的多维数组功能,并且提供了丰富的函数库处理这些数组。它将常用的数学函数都进行数组化,使得这些数学函数能够直接对数组进行操作,将本来需要在Python级别进行的循环,放到C语言的运算中,明显地提高了程序的运算速度。
scipy:主要是一些科学工具集,信号处理工具集(如线性代数使用LAPACK库,快速傅立叶变换使用FFTPACK库)及数值计算的一些工具(常微分方程求解使用ODEPACK库,非线性方程组求解以及最小值求解等)。
scikit-learn:里面有很多机器学习相关的算法(如聚类算法,SVM等)。
matplotlib:是一个画图工具,和Matlab中的画图工程类似。
python libraries for scientific computation
用于数据收集的Python库
· Beautiful Soup
· Scrapy
· Selenium
用于数据清理和数据操作的Python库
· Pandas
· PyOD
· NumPy
· Spacy
用于数据可视化的Python库
· Matplotlib
· Seaborn
· Bokeh
用于建模的Python库
· Scikit-learn
· TensorFlow
· PyTorch
用于模型解释的Python库
· Lime
· H2O
用于语音处理的Python库
· Librosa
· Madmom
· pyAudioAnalysis
用于图像处理的Python库
· OpenCV-Python
· Scikit-image
· Pillow
作为数据库的Python库
· Psycopg
· SQLAlchemy
用于模型部署的Python库
· Flask

Composition

Import modules

Pip 下载非标准库
import Modules (Libraries or packages)
Definition:
A module is a collection of Python declarations intended broadly to be used as a tool.Modules are also often referred to as “libraries” or “packages” — a package is really a directory that holds a collection of modules.
Benifits:
Module make code resuable
Usually, modules will provide functions or data types that we can then use to solve a general problem, allowing us more time to focus on the software that we are building to solve a more specific problem.
Key points:
  • from module_name import object_name, a library will include a lot of code that you don’t need that may slow down your program or conflict with existing code. Because of this, it makes sense to only import what you need.
  • Datetime
    • Random
      • Rename Namespace import module_name as name_you_pick_for_the_module
        • this name could be ambiguous or lengthy
          typing the full name every time you want to use one of its functions is laborious
      • Modules Python Files and Scope
        •  
          notion image
           
       
       
      import user-customized modules

      __init__.py的主要作用是

      1. Python中package的标识,不能删除
      2. 定义__all__用来模糊导入(from package-name import *)
      3. 编写Python代码(不建议在__init__中写python模块,可以在包中在创建另外的模块来写,尽量保证__init__.py简单)
       
      __init__.py 控制着包的导入行为
      __init__.py为空仅仅是把这个包导入,不会导入包中的模块
      __all__在__init__.py文件中,定义一个__all__变量,它控制着 from 包名 import *时导入的模块

      导入方法

      1. 直接导入import(执行文件和模块(即是.py文件)要在同个目录)
      1. 通过sys模块导入自定义模块的path
      3.
      import 文件夹.模块
      文件夹.模块.属性(方法)
      notion image
       
      notion image
       
      pylab将所有的功能函数(pyplot状态机函数,大部分时numpy里面的函数)全部导入其单独的命名空间内。为什么要这样做,是因为这样可以很好地与ipython(或者类似的IDE,比如pycharm)实现很好的交互模式。

      4. Difference and coherence

      Pandas与Numpy中axis参数的二义性

      Numpy 中 axis 轴

      作用范围

      统计函数:average、max、min、sum,比较常见的还有sort和prod

      如何理解

      简单的二位数组
      axis=0,则沿着纵轴(行)进行操作
      axis=1,则沿着横轴(列)进行操作
      多维数组
      设axis=i,则numpy沿着第i个下标变化的放下进行操作

      例子

      Pandas 中 axis 轴
       
      notion image

      Load and export data

      数据编码和解码

      检查数据类型

      pandas 读取/导出CSV文件出现乱码

       
      Python open文件操作
      Numpy 导入导出
      不同于python 原生的数据格式,可以接受不同类型的数据。numpy数据格式只能是Datatype。Python array 不同于 List 可以动态调整尺寸,数据尺寸固定。Python array 尺寸的调整是删除原数据,重新定义新变量。

      从 txt/csv 文档读取两列数据

      np.loadtxt()
      help
      loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None)
      1. fname :文件路径,若是压缩文件,会先解压(decompressed)
      1. dtype(datatype), default value: float, each row will be interpreted as an element of the array and the number of columns used must match the number of field
      1. comments: str or sequences of str the default is "#"
      1. delimiter: str seperate values default value is whitespace
      1. skiprows: int
      1. usrcols: int ot sequence
      1. unpack: bool if True , the returned array is transposed. so the arguments may be unpacked using x, y, z = loadtxt(...)
       
       
      np.genfromtxt()
      np.savetxt()
       
       
       
      Pandas 导入导出
       
      Python 读入大文件
      内存监测工具
      ipython例子
      Python 读写Excel文件
      上一篇
      模板设计模式:让你的代码结构更清晰
      下一篇
      Guide to Linux System

      Comments
      Loading...