Python3 常用模块:提升开发效率的必备工具 Python 之所以强大,很大程度上得益于其丰富的标准库和第三方模块。这些模块封装 了各种常用功能,让开发者无需重复造轮子。本文整理了 Python3 中最常用的模块,涵盖数据处理、文件操作、网络请求、日期时间等多个领域,并提供实用示例。
内置核心模块(无需安装) 1. os:操作系统交互 提供与操作系统交互的功能,如文件操作、路径处理、环境变量等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import osprint (os.getcwd()) os.makedirs("data/logs" , exist_ok=True ) print (os.listdir("." )) file_path = os.path.join("data" , "file.txt" ) print (os.path.exists(file_path))
2. sys:Python 解释器交互 用于访问 Python 解释器的变量和函数,如命令行参数、退出程序等。
1 2 3 4 5 6 7 8 9 10 11 12 13 import sysprint (f"脚本名:{sys.argv[0 ]} " )print (f"参数列表:{sys.argv[1 :]} " ) if len (sys.argv) < 2 : print ("缺少参数!" ) sys.exit(1 ) print (sys.version)
3. datetime:日期时间处理 提供日期和时间的格式化、计算等功能,比 time 模块更直观。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from datetime import datetime, timedeltanow = datetime.now() print (now.strftime("%Y-%m-%d %H:%M:%S" )) future = now + timedelta(days=3 ) print (future.strftime("%Y-%m-%d" )) date_str = "2025-01-01" date_obj = datetime.strptime(date_str, "%Y-%m-%d" ) print (type (date_obj))
4. json:JSON 数据处理 用于 JSON 格式的序列化(对象→字符串)和反序列化(字符串→对象)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import jsondata = {"name" : "Alice" , "age" : 25 , "hobbies" : ["reading" , "coding" ]} json_str = json.dumps(data, indent=2 ) print (json_str)json_str = '{"name": "Bob", "age": 30}' data = json.loads(json_str) print (data["name" ])
5. re:正则表达式 处理复杂字符串匹配、提取和替换,详见前文 “模式匹配” 章节。
1 2 3 4 5 6 import retext = "联系我们: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)
6. collections:高级数据结构 提供比内置类型更丰富的数据结构,如 defaultdict、deque、Counter 等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from collections import defaultdict, Counter, dequedd = defaultdict(list ) dd["fruits" ].append("apple" ) dd["fruits" ].append("banana" ) print (dd["fruits" ]) words = ["apple" , "banana" , "apple" , "orange" , "apple" ] word_counts = Counter(words) print (word_counts.most_common(2 )) dq = deque([1 , 2 , 3 ]) dq.append(4 ) dq.appendleft(0 ) print (dq)
提供高效的迭代器生成函数,用于循环和组合数据。
1 2 3 4 5 6 7 8 9 10 11 import itertoolscount = itertools.count(1 , 2 ) print (list (itertools.islice(count, 5 ))) colors = ["红" , "蓝" ] sizes = ["S" , "M" , "L" ] for c, s in itertools.product(colors, sizes): print (f"{c} {s} " )
常用第三方模块(需安装) 使用 pip install 模块名 安装,如 pip install requests。
1. requests:HTTP 请求 简洁高效的 HTTP 库,用于发送 GET/POST 等请求,比内置 urllib 更易用。
1 2 3 4 5 6 7 8 9 10 11 import requestsresponse = requests.get("https://api.github.com" ) print (response.status_code) print (response.json()) 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 pddata = { "Name" : ["Alice" , "Bob" , "Charlie" ], "Age" : [25 , 30 , 35 ], "City" : ["New York" , "London" , "Paris" ] } df = pd.DataFrame(data) print (df.head(2 )) print (df[df["Age" ] > 28 ]) 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 nparr = np.array([1 , 2 , 3 , 4 , 5 ]) print (arr * 2 ) matrix = np.array([[1 , 2 ], [3 , 4 ]]) print (matrix.dot(matrix)) print (np.mean(arr)) print (np.sum (arr))
4. matplotlib / seaborn:数据可视化 matplotlib 是基础绘图库,seaborn 基于它提供更美观的统计图表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import matplotlib.pyplot as pltimport seaborn as snsx = [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, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerengine = 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 BeautifulSoupimport requestsurl = "https://example.com" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser" ) print (soup.title.text) links = soup.find_all("a" ) for link in links: print (link.get("href" ))
模块使用最佳实践
按需导入 :避免 import *,只导入需要的功能,减少内存占用:
1 2 from datetime import datetime
处理依赖 :使用 requirements.txt 管理第三方模块版本:
1 2 3 requests==2.31.0 pandas==2.0.3 numpy==1.25.2
安装命令:pip install -r requirements.txt
异常处理 :使用模块时注意捕获可能的异常:
1 2 3 4 5 6 7 8 import jsontry : with open ("data.json" , "r" ) as f: data = json.load(f) except FileNotFoundError: print ("文件不存在" ) except json.JSONDecodeError: print ("JSON 格式错误" )
查阅文档 :模块功能丰富,建议参考官方文档:
总结 Python 的模块生态极大简化了开发工作,本文列举的只是最常用的一部分:
内置模块 :覆盖基础功能,无需安装,优先使用
第三方模块 :针对特定领域(如数据分析、网络请求),按需安装