0%

Python3 常用模块:提升开发效率的必备工具

Python3 常用模块:提升开发效率的必备工具

Python 之所以强大,很大程度上得益于其丰富的标准库和第三方模块。这些模块封装 了各种常用功能,让开发者无需重复造轮子。本文整理了 Python3 中最常用的模块,涵盖数据处理、文件操作、网络请求、日期时间等多个领域,并提供实用示例。

内置核心模块(无需安装)

1. os:操作系统交互

提供与操作系统交互的功能,如文件操作、路径处理、环境变量等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os

# 获取当前工作目录
print(os.getcwd()) # /home/user/project

# 创建目录
os.makedirs("data/logs", exist_ok=True) # exist_ok=True 避免目录已存在报错

# 列出目录内容
print(os.listdir(".")) # 列出当前目录文件

# 路径拼接(跨平台兼容)
file_path = os.path.join("data", "file.txt") # data/file.txt(Linux)或 data\file.txt(Windows)

# 判断路径是否存在
print(os.path.exists(file_path)) # False

2. sys:Python 解释器交互

用于访问 Python 解释器的变量和函数,如命令行参数、退出程序等。

1
2
3
4
5
6
7
8
9
10
11
12
13
import sys

# 命令行参数(sys.argv[0] 是脚本名)
print(f"脚本名:{sys.argv[0]}")
print(f"参数列表:{sys.argv[1:]}") # 运行脚本时传入的参数

# 退出程序
if len(sys.argv) < 2:
print("缺少参数!")
sys.exit(1) # 非0状态码表示异常退出

# Python 版本信息
print(sys.version) # # 3.11.6 (main, Oct 19 2023, 03:03:33) [Clang 12.0.0 (clang-1200.0.32.29)]

3. datetime:日期时间处理

提供日期和时间的格式化、计算等功能,比 time 模块更直观。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from datetime import datetime, timedelta

# 获取当前时间
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-09-16 12:17:12

# 时间计算(3天后)
future = now + timedelta(days=3)
print(future.strftime("%Y-%m-%d")) # 2025-09-19

# 字符串转时间
date_str = "2025-01-01"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(type(date_obj)) # <class 'datetime.datetime'>

4. json:JSON 数据处理

用于 JSON 格式的序列化(对象→字符串)和反序列化(字符串→对象)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import json

# Python 字典转 JSON 字符串
data = {"name": "Alice", "age": 25, "hobbies": ["reading", "coding"]}
json_str = json.dumps(data, indent=2) # indent 美化输出
print(json_str)
# {
# "name": "Alice",
# "age": 25,
# "hobbies": [
# "reading",
# "coding"
# ]
# }

# JSON 字符串转 Python 字典
json_str = '{"name": "Bob", "age": 30}'
data = json.loads(json_str)
print(data["name"]) # Bob

5. re:正则表达式

处理复杂字符串匹配、提取和替换,详见前文 “模式匹配” 章节。

1
2
3
4
5
6
import re

# 提取文本中的邮箱
text = "联系我们:info@example.com 或 support@company.org"
emails = re.findall(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", text)
print(emails) # ['info@example.com', 'support@company.org']

6. collections:高级数据结构

提供比内置类型更丰富的数据结构,如 defaultdictdequeCounter 等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from collections import defaultdict, Counter, deque

# defaultdict:默认值字典(避免 KeyError)
dd = defaultdict(list) # 默认值为列表
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dd["fruits"]) # ['apple', 'banana']

# Counter:计数工具
words = ["apple", "banana", "apple", "orange", "apple"]
word_counts = Counter(words)
print(word_counts.most_common(2)) # [('apple', 3), ('banana', 1)]

# deque:高效双端队列(适合频繁首尾操作)
dq = deque([1, 2, 3])
dq.append(4) # 右侧添加
dq.appendleft(0) # 左侧添加
print(dq) # deque([0, 1, 2, 3, 4])

7. itertools:迭代器工具

提供高效的迭代器生成函数,用于循环和组合数据。

1
2
3
4
5
6
7
8
9
10
11
import itertools

# 生成无限迭代器(配合 islice 限制数量)
count = itertools.count(1, 2) # 从1开始,步长2
print(list(itertools.islice(count, 5))) # [1, 3, 5, 7, 9]

# 组合两个列表的元素
colors = ["红", "蓝"]
sizes = ["S", "M", "L"]
for c, s in itertools.product(colors, sizes):
print(f"{c}{s}") # 红S、红M、红L、蓝S、蓝M、蓝L

常用第三方模块(需安装)

使用 pip install 模块名 安装,如 pip install requests

1. requests:HTTP 请求

简洁高效的 HTTP 库,用于发送 GET/POST 等请求,比内置 urllib 更易用。

1
2
3
4
5
6
7
8
9
10
11
import requests

# 发送 GET 请求
response = requests.get("https://api.github.com")
print(response.status_code) # 200(成功)
print(response.json()) # 解析 JSON 响应

# 发送 POST 请求(带参数)
data = {"username": "test", "password": "123"}
response = requests.post("https://httpbin.org/post", data=data)
print(response.text) # 响应文本

2. pandas:数据分析

处理结构化数据的利器,支持表格操作、数据清洗、聚合分析等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import pandas as pd

# 创建 DataFrame(表格数据)
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["New York", "London", "Paris"]
}
df = pd.DataFrame(data)

# 基本操作
print(df.head(2)) # 显示前2行
print(df[df["Age"] > 28]) # 筛选年龄>28的行

# 保存为 CSV
df.to_csv("users.csv", index=False)

3. numpy:数值计算

用于高效处理大型多维数组和矩阵,提供数学运算函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np

# 创建数组
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2) # [ 2 4 6 8 10]

# 二维数组(矩阵)
matrix = np.array([[1, 2], [3, 4]])
print(matrix.dot(matrix)) # 矩阵乘法:[[ 7 10], [15 22]]

# 统计函数
print(np.mean(arr)) # 平均值:3.0
print(np.sum(arr)) # 总和:15

4. matplotlib / seaborn:数据可视化

matplotlib 是基础绘图库,seaborn 基于它提供更美观的统计图表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
import seaborn as sns

# 示例数据
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# 绘制折线图
plt.figure(figsize=(8, 4))
sns.lineplot(x=x, y=y)
plt.title("简单折线图")
plt.xlabel("X轴")
plt.ylabel("Y轴")
plt.show()

5. sqlalchemy:数据库交互

ORM(对象关系映射)工具,支持多种数据库(MySQL、PostgreSQL 等)。

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
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 连接 SQLite 数据库(文件数据库)
engine = create_engine("sqlite:///test.db")
Base = declarative_base()

# 定义模型
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)

# 创建表
Base.metadata.create_all(engine)

# 插入数据
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Alice", age=25))
session.commit()

# 查询数据
users = session.query(User).all()
for user in users:
print(f"ID: {user.id}, Name: {user.name}")

6. beautifulsoup4:网页解析

用于解析 HTML/XML 文档,提取网页数据(爬虫常用)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from bs4 import BeautifulSoup
import requests

# 获取网页内容
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

# 提取标题
print(soup.title.text) # Example Domain

# 提取所有链接
links = soup.find_all("a")
for link in links:
print(link.get("href")) # 链接地址

模块使用最佳实践

  1. 按需导入:避免 import *,只导入需要的功能,减少内存占用:

    1
    2
    from datetime import datetime  # 推荐
    # 不推荐:from datetime import *
  2. 处理依赖:使用 requirements.txt 管理第三方模块版本:

    1
    2
    3
    requests==2.31.0
    pandas==2.0.3
    numpy==1.25.2

    安装命令:pip install -r requirements.txt

  3. 异常处理:使用模块时注意捕获可能的异常:

    1
    2
    3
    4
    5
    6
    7
    8
    import json
    try:
    with open("data.json", "r") as f:
    data = json.load(f)
    except FileNotFoundError:
    print("文件不存在")
    except json.JSONDecodeError:
    print("JSON 格式错误")
  4. 查阅文档:模块功能丰富,建议参考官方文档:

总结

Python 的模块生态极大简化了开发工作,本文列举的只是最常用的一部分:

  • 内置模块:覆盖基础功能,无需安装,优先使用
  • 第三方模块:针对特定领域(如数据分析、网络请求),按需安装

欢迎关注我的其它发布渠道