讲解
Python 的口号是「自带电池」(batteries included):安装即得的三百多个标准库模块覆盖了日常开发的绝大多数需求,动手写轮子之前先想想标准库里有没有现成的。本章挑最高频的八个快速过一遍,每个都值得回头翻官方文档细读。
文本与数据:re 正则表达式(re.findall 找全部、re.search 找第一个、re.sub 替换);json 处理 JSON(json.loads 字符串转对象、json.dumps 对象转字符串,中文记得 ensure_ascii=False);collections 提供增强容器——Counter 一行计数、defaultdict 自动初始化缺失键、deque 双端队列、namedtuple 具名元组。
数字与时间:math 数学函数(sqrt、floor、ceil、pi、isclose);random 随机(randint、choice、shuffle、sample,测试时用 seed 固定结果);datetime 日期时间(date、datetime、timedelta 做加减,strptime/strftime 与字符串互转);statistics 基础统计(mean、median、stdev)。
系统与工具:pathlib 路径(文件一章已详讲);os 与 sys 环境交互(os.environ 读环境变量、sys.argv 读命令行参数);itertools 迭代器工具箱(islice、chain、combinations、groupby);functools 函数工具(lru_cache、wraps、partial、reduce)。还有 subprocess 调外部命令、logging 规范日志、unittest/pytest 做测试——先混个脸熟,用到再深查。
示例
# json:数据交换的普通话
import json
data = {'name': '小明', 'tags': ['python', '教程'], 'score': 95.5}
text = json.dumps(data, ensure_ascii=False)
print('序列化:', text)
print('解析回来:', json.loads(text)['tags'])
# collections.Counter:一行计数
from collections import Counter, defaultdict
words = 'the quick brown fox jumps over the lazy dog the'.split()
print('词频前三:', Counter(words).most_common(3))
# defaultdict:缺失键自动初始化
groups = defaultdict(list)
for word in words:
groups[len(word)].append(word)
print('按长度分组:', dict(groups))
# re:正则提取
import re
log = 'user_id=42 action=login user_id=7 action=logout'
print('所有 user_id:', re.findall(r'user_id=(\d+)', log))
print('替换:', re.sub(r'\d+', '***', log))
# datetime:时间与计算
from datetime import date, timedelta
today = date(2026, 8, 9)
deadline = today + timedelta(days=30)
print('30 天后:', deadline, ',是周', deadline.isoweekday())
print('格式化:', deadline.strftime('%Y年%m月%d日'))
# math 与 statistics
import math
import statistics
print('数学:', math.sqrt(2), math.isclose(0.1 + 0.2, 0.3))
scores = [88, 75, 92, 60, 85]
print('统计:', statistics.mean(scores), statistics.median(scores))
# random:可复现的随机
import random
random.seed(2026)
deck = ['A', 'K', 'Q', 'J']
random.shuffle(deck)
print('洗牌:', deck, ',抽两张:', random.sample(deck, 2))
# itertools:迭代器工具箱
from itertools import chain, combinations
print('拼接:', list(chain([1, 2], [3, 4])))
print('组合:', list(combinations(['甲', '乙', '丙'], 2)))
常见坑
- 重复造轮子:手写 CSV 解析、日期计算、Base64 之前先查标准库(csv、datetime、base64 全有),自己造的大概率有边角 bug。
- json.dumps 中文变 \uXXXX:加 ensure_ascii=False 保留原文;loads/dumps 是字符串级,load/dump(无 s)是文件级,别记混。
- datetime 与字符串直接比较:'2026-08-09' < '2026-08-10' 这种字符串比较只是碰巧可用,跨格式就出错。先 strptime 解析成对象再比较。
- random 用于安全场景:random 是伪随机,不抗预测。生成密码、令牌请用 secrets 模块。
小结
re/json/collections/datetime/math/random/itertools/functools 是高频八件套;动手前先查标准库。最后一章:用虚拟环境把工程实践收尾。