8
模块与包:组织你的代码
Modules, Packages & pip
代码写到 500 行还堆在一个文件里,就该拆了。模块就是一个 .py 文件,包就是一个装了模块的文件夹。Python 自带一堆标准库,pip 能装上万个第三方包。学会 import,你就站在了巨人肩膀上。
import 的几种姿势
import os # 整个模块,用 os.listdir()
from os import listdir, getcwd # 只要这两个函数,直接 listdir()
import numpy as np # 起别名,业界惯例
from pathlib import Path # 推荐:只要类本身
# 别写 from os import *——会污染命名空间,别人读你代码不知道哪来的
常用标准库速查
| 库 | 干嘛用 |
|---|---|
os / sys | 操作系统交互、命令行参数、退出程序。 |
pathlib | 路径操作(Python 3.4+ 推荐,比 os.path 优雅)。 |
datetime / time | 日期时间。 |
json | 读写 JSON。 |
re | 正则表达式。 |
random / math | 随机数、数学函数。 |
collections | defaultdict、Counter、namedtuple。 |
itertools / functools | 迭代器工具、lru_cache、reduce。 |
argparse | 解析命令行参数。 |
logging | 打日志。 |
pip 与虚拟环境 venv
# 装第三方包
pip3 install requests
pip3 install "numpy==2.1.0" # 锁定版本
# 把当前项目用了哪些包记下来
pip3 freeze > requirements.txt
# 换台机器,一键装齐
pip3 install -r requirements.txt
# 虚拟环境:每个项目独立一套包,互不打架
python3 -m venv .venv # 在当前目录建一个
# 激活(Mac/Linux):
source .venv/bin/activate
# 激活(Windows PowerShell):
# .venv\Scripts\Activate.ps1
# 激活后命令行前面会出现 (.venv),装的包都进这个小环境
deactivate # 退出虚拟环境
collections 详解:三个最爱用的
标准库 collections 里有几个"升级版"容器,解决日常 80% 的小麻烦。
from collections import Counter, namedtuple
# Counter:计数器,一行搞定"这堆词出现了几次"
words = ["苹果", "香蕉", "苹果", "橙子", "苹果", "香蕉"]
cnt = Counter(words)
print(cnt) # Counter({'苹果': 3, '香蕉': 2, '橙子': 1})
print(cnt.most_common(2)) # [('苹果', 3), ('香蕉', 2)] 出现最多的前2个
# namedtuple:带名字的元组,比元组可读
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4 比 p[0] p[1] 清楚多了
functools:缓存与偏函数
from functools import lru_cache, reduce, partial
# lru_cache:自动缓存函数返回值,同样的参数不重算
@lru_cache(maxsize=128)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
print(fib(100)) # 没缓存要跑一年,缓存后瞬间出结果
# reduce:把一串东西"折叠"成一个
print(reduce(lambda a, b: a*b, [1,2,3,4])) # 24 阶乘
# partial:固定一个参数,造个新函数
power2 = partial(pow, exp=2)
print(power2(5)) # 25
正则表达式 re:文本处理瑞士军刀
import re
text = "我的电话是 13812345678,备用 13987654321"
# findall:找出所有匹配
phones = re.findall(r"1[3-9]\d{9}", text)
print(phones) # ['13812345678', '13987654321']
# sub:替换
clean = re.sub(r"\d", "*", "我的密码是 123456")
print(clean) # 我的密码是 ******
# split:按规则切分
parts = re.split(r"[,;,;]", "a,b;c,d;e")
print(parts) # ['a', 'b', 'c', 'd', 'e']
requirements.txt 老了,pyproject.toml 才是新宠
新项目建议用 pyproject.toml(PEP 621),一个文件同时写依赖、版本约束、构建配置。pip install . 就能装。requirements.txt 仍然能用、到处都是,但它只管"装哪些包",不管"怎么打包这个项目"。新项目:pyproject.toml;老项目:requirements.txt 继续用。