标准库精讲
# Python 标准库精讲
Python 的一个巨大优势在于其“开箱即用”(batteries included)的哲学。这意味着,当你安装 Python 时,就已经附带了一个庞大而功能强大的标准库。这个库包含了用于处理各种常见任务的模块,从文本处理到网络编程,无需额外安装任何第三方包。
掌握标准库是提升 Python 编程效率的关键。本章将精讲其中最核心、最常用的一些模块。
# 1. 文本处理模块 (Text Processing)
# re
- 正则表达式
re
模块让 Python 具备了强大的正则表达式功能,用于复杂的字符串匹配和处理。
re.search(pattern, string)
: 在字符串中搜索第一个匹配项,返回一个匹配对象,否则返回None
。re.match(pattern, string)
: 从字符串的开头开始匹配,如果开头不匹配,则返回None
。re.findall(pattern, string)
: 查找所有匹配项,并以列表形式返回。re.sub(pattern, repl, string)
: 替换匹配项。
import re
text = "我的电话是 138-1234-5678, 另一个是 189-8765-4321。"
phone_pattern = r"\d{3}-\d{4}-\d{4}"
# 查找所有电话号码
phones = re.findall(phone_pattern, text)
print(f"找到的号码: {phones}") # 输出: ['138-1234-5678', '189-8765-4321']
# 替换号码,保护隐私
safe_text = re.sub(phone_pattern, "XXX-XXXX-XXXX", text)
print(f"处理后的文本: {safe_text}")
2
3
4
5
6
7
8
9
10
11
12
# 2. 数据结构与容器模块 (Data Structures)
# collections
- 高性能容器
collections
模块提供了标准数据类型(dict
, list
, set
, tuple
)的替代品,功能更强大。
namedtuple
: 创建带有命名字段的元组子类,使代码更具可读性。deque
: 双端队列,支持从两端快速地添加和删除元素。Counter
: 字典的子类,用于计算可哈希对象的出现次数。defaultdict
: 字典的子类,当访问不存在的键时,会自动调用一个工厂函数来提供默认值。
from collections import namedtuple, deque, Counter, defaultdict
# namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(f"点坐标: x={p.x}, y={p.y}")
# deque
d = deque(['a', 'b', 'c'])
d.appendleft('x')
d.append('y')
print(f"双端队列: {d}") # 输出: deque(['x', 'a', 'b', 'c', 'y'])
# Counter
word_counts = Counter("hello world")
print(f"字母统计: {word_counts}") # 输出: Counter({'l': 3, 'o': 2, ...})
print(f"字母 'l' 出现了 {word_counts['l']} 次")
# defaultdict
# 如果访问不存在的键,默认创建一个空列表
word_groups = defaultdict(list)
word_groups['fruits'].append('apple')
print(word_groups['fruits']) # 输出: ['apple']
print(word_groups['animals']) # 输出: [] (因为访问了,所以自动创建)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# datetime
- 日期和时间处理
这是处理日期和时间的核心模块。
datetime.now()
: 获取当前日期和时间。datetime.strptime(date_string, format)
: 将字符串解析为datetime
对象。datetime_obj.strftime(format)
: 将datetime
对象格式化为字符串。timedelta
: 表示两个日期或时间之间的差。
from datetime import datetime, timedelta
now = datetime.now()
print(f"当前时间: {now}")
# 格式化输出
print(f"格式化: {now.strftime('%Y-%m-%d %H:%M:%S')}")
# 字符串解析
dt = datetime.strptime("2023-01-01 12:30", "%Y-%m-%d %H:%M")
print(f"解析结果: {dt}")
# 时间计算
three_days_later = now + timedelta(days=3, hours=5)
print(f"三天五小时后: {three_days_later.strftime('%Y-%m-%d')}")
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 3. 数学与随机数模块 (Math & Random)
# math
- 数学函数
提供了标准 C 库中的数学函数。
import math
print(f"圆周率 Pi: {math.pi}")
print(f"9的平方根: {math.sqrt(9)}") # 3.0
print(f"向上取整: {math.ceil(4.2)}") # 5
print(f"向下取整: {math.floor(4.8)}") # 4
2
3
4
5
6
# random
- 生成伪随机数
用于生成各种类型的随机数。
import random
# 生成一个 [0.0, 1.0) 之间的随机浮点数
print(f"随机浮点数: {random.random()}")
# 生成一个 [1, 10] 之间的随机整数
print(f"随机整数: {random.randint(1, 10)}")
# 从序列中随机选择一个元素
choices = ['石头', '剪刀', '布']
print(f"随机选择: {random.choice(choices)}")
# 将一个序列原地打乱
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"打乱后: {numbers}")
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 4. 文件与目录访问 (File & Directory Access)
# os
- 操作系统接口
os
模块提供了与操作系统交互的功能,如文件路径操作、目录管理等。
# pathlib
- 面向对象的文件系统路径 (推荐)
从 Python 3.4 开始,pathlib
模块提供了一种更现代、更直观的面向对象的方式来处理文件系统路径,强烈推荐使用它来替代 os.path
。
- 创建路径:
Path()
- 拼接路径: 使用
/
操作符。 - 常用方法:
exists()
,is_dir()
,is_file()
,glob()
,read_text()
,write_text()
。
from pathlib import Path
# 获取当前工作目录
current_dir = Path.cwd()
print(f"当前目录: {current_dir}")
# 路径拼接
my_file = current_dir / "data" / "test.txt"
print(f"拼接后的路径: {my_file}")
# 创建目录 (如果父目录不存在,也一并创建)
my_file.parent.mkdir(parents=True, exist_ok=True)
# 写入和读取文本
my_file.write_text("你好,pathlib!", encoding="utf-8")
content = my_file.read_text(encoding="utf-8")
print(f"文件内容: {content}")
# 检查文件是否存在
print(f"文件是否存在? {my_file.exists()}")
# 遍历目录下的所有 .py 文件
for py_file in Path('.').glob('**/*.py'):
print(py_file)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 5. 数据持久化与交换 (Data Persistence & Exchange)
# json
- JSON 编码和解码
json
模块用于在 Python 对象和 JSON 字符串之间进行转换,是 Web 开发和 API 交互的事实标准。
json.dumps(obj)
: 将 Python 对象序列化为 JSON 格式的字符串。json.loads(json_str)
: 将 JSON 格式的字符串反序列化为 Python 对象。
import json
# Python 字典
data = {
"name": "Alice",
"age": 25,
"isStudent": False,
"courses": ["Math", "Physics"]
}
# 序列化
json_string = json.dumps(data, indent=4, ensure_ascii=False)
print("JSON 字符串:")
print(json_string)
# 反序列化
parsed_data = json.loads(json_string)
print("\n解析后的 Python 对象:")
print(parsed_data["name"])
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# pickle
- Python 对象序列化
pickle
模块可以将几乎任何 Python 对象转换为一个字节流,以便存储或传输。
警告: pickle
不安全!不要反序列化来自不可信来源的数据,因为它可能执行任意代码。
import pickle
class User:
def __init__(self, name):
self.name = name
user = User("Bob")
# 序列化
pickled_user = pickle.dumps(user)
print(f"序列化后的字节: {pickled_user}")
# 反序列化
unpickled_user = pickle.loads(pickled_user)
print(f"反序列化后的对象名: {unpickled_user.name}")
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 6. 实用工具模块 (Utilities)
# sys
- 系统特定参数和函数
sys
模块让你能访问由解释器使用或维护的变量,以及与解释器强烈交互的函数。
sys.argv
: 命令行参数列表。sys.platform
: 操作系统平台标识。sys.exit()
: 退出 Python 程序。
import sys
print(f"操作系统平台: {sys.platform}")
# 在命令行运行 `python your_script.py arg1 arg2`
# print(f"命令行参数: {sys.argv}")
2
3
4
5
# itertools
- 高效循环的迭代器
itertools
模块提供了用于创建高效迭代器的工具,用于处理排列、组合、笛卡尔积等。
import itertools
# 排列
print(list(itertools.permutations('ABC', 2)))
# 输出: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
# 组合
print(list(itertools.combinations('ABC', 2)))
# 输出: [('A', 'B'), ('A', 'C'), ('B', 'C')]
# 无限循环
# counter = itertools.cycle(['On', 'Off'])
# next(counter) # 'On'
# next(counter) # 'Off'
# next(counter) # 'On'
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 7. 网络编程 (Networking)
标准库也提供了支持网络通信的基础模块。
# urllib.request
- 发起 HTTP 请求
这个模块可以让你像浏览器一样访问网页。
urllib.request.urlopen(url)
: 打开一个 URL,返回一个响应对象。response.read()
: 读取响应内容(字节流)。response.status
: 获取 HTTP 状态码(例如 200 表示成功)。
import urllib.request
import json
try:
# 发起一个 GET 请求
url = "https://httpbin.org/get"
with urllib.request.urlopen(url) as response:
print(f"状态码: {response.status}")
# 读取并解码内容
content_bytes = response.read()
content_str = content_bytes.decode('utf-8')
data = json.loads(content_str)
print(f"你的IP地址是: {data['origin']}")
except Exception as e:
print(f"请求失败: {e}")
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
注意: urllib
功能强大但使用起来较为繁琐。在实际项目中,绝大多数开发者会选择使用第三方库 requests
,它的 API 设计得非常友好和简洁。
# socket
- 底层网络接口
socket
模块提供了标准的 BSD Sockets API,允许你进行更底层的网络编程,例如构建自己的 TCP/UDP 客户端和服务器。
# 一个简单的 TCP 客户端示例
import socket
# try:
# with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# s.connect(("www.python.org", 80))
# s.sendall(b"GET / HTTP/1.1\r\nHost: www.python.org\r\n\r\n")
# response = s.recv(1024)
# print(response.decode('utf-8'))
# except Exception as e:
# print(f"Socket 连接失败: {e}")
2
3
4
5
6
7
8
9
10
11
这只是标准库的冰山一角。花时间探索官方文档,你会发现更多强大的工具,它们能极大地简化你的编程工作。