zxpnet网站 zxpnet网站
首页
前端
后端服务器
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

zxpnet

一个爱学习的java开发攻城狮
首页
前端
后端服务器
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • python基础

    • python3基础
    • python爬虫开发
    • python web开发
    • wxpy微信开发
    • 尹成python
    • python常见库
      • 一、functools
        • 01、reduce
        • 02、partial
        • 03、lru_cache
        • lru_cache的本质
        • cache使用的场合
        • lru_cache与redis区别
      • tracemalloc
      • Jupyter
      • 解析xml
        • 方式一:tree方式
        • 方式二:Dom方式
      • 随机库random、radar、 m-mock
      • pygame
      • requests
      • pywin32
      • colorsys
      • 快速清理pip库
    • python金融开发
    • python文件操作
    • python正则表达式
    • python面向对象
    • python模块化
    • python线程与并发
    • python数据库
    • python整合redis
  • python爬虫

  • python库

  • 树莓派
  • Arduino
  • STM32
  • kali linux
  • python培训班
  • python
  • python基础
shollin
2023-02-02
目录

python常见库

# 一、functools

# 01、reduce

语法:functools.reduce(function, iterable[, initializer])

该函数与 Python 内置的 reduce() 函数相同。 函数一般用lambda方式写, 需要接收两个参数;

from functools import reduce

l = [1,2,3]
#result = reduce( lambda x:x, l); #<lambda>() takes 1 positional argument but 2 were given, 函数需要接收两个参数

result = reduce( lambda x,y: print(x,y), l); # 将函数的返回值放入下一次计算, 1 2 ,None 3, None
print(result);
1
2
3
4
5
6
7

# 02、partial

偏函数, 语法:functools.partial(func[, *args][, **keywords])

  • 把函数部分参数固定下来,相当于为部分的参数添加了固定的默认值,形成一个新的函数,并返回这个新函数
  • 这个新函数是对原函数的封装
  • 通过inspect.signature 查看函数的签名,以免传参出错
from functools import partial

def add(x:int ,y:int ):
    print(x,y);
    return x+y;
    
newFun = partial(add, 33); # 固定了第一个参数x=33,相当于给了缺省值 或者 y=XXX
newFun2 = partial(add, y=33); # 

newFun(11);  #这时y=11
newFun(y=11); # newFun(x=1) 会报错

print(inspect.signature(newFun)); # (y: int)
print(inspect.signature(newFun2)); #  (x: int, *, y: int = 33)

def add2(x,y,*args):
    print(x,y,args);
    return x+y+sum(args)

newAdd = partial(add2,1,3,4,5);
newAdd(); # 1 3 (4, 5)
newAdd(1,2); #1 3 (4, 5, 1, 2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

源码文档:file:///D:/Python/Python311/Doc/html/library/functools.html?highlight=partial#functools.partial

def partial(func, /, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = {**keywords, **fkeywords}
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
1
2
3
4
5
6
7
8

# 03、lru_cache

  • Iru即Least-recently-used,最近最少使用。cache缓存

  • 如果maxsize设置为None,则禁用LRU功能,并且缓存可以无限制增长。当maxsize是二的幂时LRU功能执行得最好

  • 如果typed设置为True,则不同类型的函数参数将单独缓存。例如,f(3)和f(3.0)将被视为具有不同结果的不同调用

  • lru_cache不支持可变参数

import time
from functools import lru_cache


@lru_cache  # add = lru_cache(add);
def add(x=3,y=5):
    time.sleep(1);
    print("-"*30);
    return x+y;

print(1,add(3,5));
print(2,add(3,5)); # 缓存命中
print(3,add(3.0,5.0)); # 缓存命中, typed=False时会命中,typed=True缓存不命中
print(4,add()); # 缓存未命中
print(5,add(3)); # 缓存未命中
print(6,add(3,y=5)); # 缓存未命中
print(7,add(x=3,y=5)); # 缓存未命中

@lru_cache() # fib = lru_cache()(fib);
def fib(n):
    return 1 if n<3 else fib(n-1) + fib(n-2)

print(fib(31));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# lru_cache的本质

内部使用了一个字典; 字典的key由_make_key函数生成,因此lru_cache所有参数必须可哈希hash

image-20230223141713399

# cache使用的场合

1、不变: 一段时间内,不变化;幂等性,给定一个输入一定返回一个不变的结果

2、计算代价高:以空间换时间

3、使用频度高

# lru_cache与redis区别

缓存 缓存位置 是否支持可变参数 是否支持分布式 是否支持过期时间设置 支持的数据结构 需单独安装
redis 缓存在redis管理的内存中 是 是 是 支持5种数据结构 是
lru_cache 缓存在应用进程的内存中,应用被关闭则被清空 否 否 否 字典(参数为:key,结果为:value) 否

# tracemalloc

标准库tracemalloc,可以统计内存使用情况

# Jupyter

Jupyter Notebook(此前被称为 IPython notebook)是一个交互式笔记本,支持运行 40 多种编程语言。

Jupyter Notebook 的本质是一个 Web应用程序,便于创建和共享程序文档,支持实时代码,数学方程,可视化和markdown。 用途包括:数据清理和转换,数值模拟,统计建模,机器学习等等

pip install jupyterlab 
jupyter-lab

pip install notebook
jupyter notebook
jupyter notebook --no-browser --port <port_number>

1
2
3
4
5
6
7

image-20230202145917469

参考:

Jupyter Notebook介绍、安装及使用教程 (opens new window)

# 解析xml

Python 允许使用两个模块解析这些 XML 文档,即 xml.etree.ElementTree 模块和 Minidom(最小 DOM 实现)。解析意味着从文件中读取信息,并通过识别特定 XML 文件的各个部分将其拆分为多个片段。让我们进一步了解如何使用这些模块来解析 XML 数据。

# 方式一:tree方式

xml.etree.ElementTree模块帮助我们将 XML 数据格式化为树结构,这是分层数据的最自然表示。元素类型允许在内存中存储分层数据结构,并具有以下属性:

Property Description
Tag 一个字符串,表示正在存储的数据类型
Attributes 由存储为字典的许多属性组成
Text String 包含需要显示的信息的文本字符串
Tail String 如有必要,也可以有尾弦
Child Elements 由许多存储为序列的子元素组成
"""
api文档:https://docs.python.org/3/library/xml.etree.elementtree.html

参考文章: https://mp.weixin.qq.com/s/mXA_mBKSQrZiJlqDi1twjg

"""

from xml.etree import ElementTree
from xml.etree.ElementTree import Element

tree: ElementTree = ElementTree.parse('country_data.xml')
root: Element = tree.getroot()  # Element

for ele in root:
    print(ele.tag, ele.attrib, ele.text);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 方式二:Dom方式

from xml.dom import minidom
from xml.dom.minidom import Document, Element

doc:Document = minidom.parse("country_data.xml") #返回 xml.dom.minidom.Document

print(doc);

country:Element= doc.getElementsByTagName('country')[0];  #DOM Element
print(country.nodeName);
1
2
3
4
5
6
7
8
9

https://www.runoob.com/python/python-xml.html

# 随机库random、radar、 m-mock

pip install m-mock,radar -i https://pypi.tuna.tsinghua.edu.cn/simple
1
import random
from x_mock.m_mock import m_mock, MockM

m_mock.mock("@string("number", 1, 3)"):773
m_mock.mock("@string("symbol", 1, 3)"):#(<
m_mock.mock("@string("aeiou", 1, 3)"):eaa
m_mock.mock("@string("chinese", 1, 3)"):太主截
m_mock.mock("@string("cn_symbol", 1, 3)"):『“
m_mock.mock("@string("cn_string", 3, 9)"):〕壁辨钻眠素举沾。
m_mock.mock("@string("cn_string", 1)"):柔

m_mock.mock("@cname()"):梁恒蹄
m_mock.mock("@cname(3)"):臧倡荷
m_mock.mock("@last()"):Smith
m_mock.mock("@first()"):Kennet
m_mock.mock("@name()"):Jessica Jackson
m_mock.mock("@name(True)"):Melissa Mark Davis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

python 生成随机数据,随机中文,英文,数字,姓名等 (opens new window)

# pygame

pip install pygame
1

参考:

pygame官方文档 (opens new window)

# requests

pip install requests

1
2

# pywin32

import win32clipboard as w
import win32con
import win32api
import win32gui
import time

#把文字放入剪贴板
def setText(aString):
	w.OpenClipboard()
	w.EmptyClipboard()
	w.SetClipboardData(win32con.CF_UNICODETEXT,aString)
	w.CloseClipboard()
	
#模拟ctrl+V
def ctrlV():
	win32api.keybd_event(17,0,0,0) #按下ctrl
	win32api.keybd_event(86,0,0,0) #按下V
	win32api.keybd_event(86,0,win32con.KEYEVENTF_KEYUP,0)#释放V
	win32api.keybd_event(17,0,win32con.KEYEVENTF_KEYUP,0)#释放ctrl
	
#模拟alt+s
def altS():
	win32api.keybd_event(18,0,0,0)
	win32api.keybd_event(83,0,0,0)
	win32api.keybd_event(83,0,win32con.KEYEVENTF_KEYUP,0)
	win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0)
# 模拟enter
def enter():
	win32api.keybd_event(13,0,0,0)
	win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0)
#模拟鼠标单击
def click():
	win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
	win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
#移动鼠标的位置
def movePos(x,y):
	win32api.SetCursorPos((x,y))
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

参考:

如何利用 python 向微信群里定时发送消息 (opens new window)

# colorsys

colorsys--- 颜色系统间的转换 (opens new window)

# 快速清理pip库

pip安装包
pip install 所需安装包名字

pip查看已安装的包
pip show --files 安装包名字

pip检查哪些包需要更新
pip list --outdate

pip升级包
pip install --upgrade 安装包名字 

pip卸载安装包
pip uninstall  安装包名字

生成 requirements.txt
pip freeze >requirements.txt
pip3 freeze >requirements.txt

安装requirements.txt依赖:
pip install -r requirements.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

python项目中必须包含一个 requirements.txt 文件,用于记录所有依赖包及其精确的版本号,以便进行新环境的部署。日常开发中安装Python第三方包的时候,很容易造成多装了非必要的第三方库,手动一个个卸载又十分繁琐。可反向利用 requirements.txt 实现快速卸载第三方包的需求。

requirements.txt,内容举例:

certifi==2021.5.30
charset-normalizer==2.0.6
idna==3.2
requests==2.26.0
selenium==3.141.0
urllib3==1.26.7
1
2
3
4
5
6

前面是包名 == 后是对应包名的详细版本号

# 将全部第三方包冻结到 requirements.txt
pip freeze>requirements.txt

# 卸载所有的第三方包,遇到判断,输入yes / y
pip uninstall -r requirements.txt -y

#安装requirements.txt依赖
pip install -r requirements.txt

# 查看 pip 第三方包安装列表
pip list
1
2
3
4
5
6
7
8
9
10
11
尹成python
python金融开发

← 尹成python python金融开发→

最近更新
01
国际象棋
09-15
02
成语
09-15
03
自然拼读
09-15
更多文章>
Theme by Vdoing | Copyright © 2019-2023 zxpnet | 粤ICP备14079330号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式