Appearance
模块与包——import、pip、虚拟环境
概念讲解
模块(Module):一个 .py 文件就是一个模块,可以被其他文件导入使用。
包(Package):包含 __init__.py 的文件夹,可以包含多个模块。
mypackage/
__init__.py # 包初始化文件
utils.py # 模块
config.py # 模块
subpackage/
__init__.py
helpers.py为什么需要虚拟环境?
- 不同项目依赖不同版本的库
- 避免全局安装的包互相污染
- 用
venv创建轻量级虚拟环境(Python 3.3+ 内置)
代码示例
模块的导入方式
python
# 方式1:导入整个模块
import math
print(math.sqrt(16)) # 4.0
# 方式2:导入特定内容(推荐,减少命名空间污染)
from math import sqrt, pi
print(sqrt(16)) # 4.0
# 方式3:给模块起别名
import pandas as pd
import numpy as np
# 方式4:导入时重命名
from math import sqrt as square_root
# 条件导入(处理不同平台/版本)
try:
import mymodule # 自定义模块
except ImportError:
print("mymodule 未安装,使用替代方案")创建一个自己的包
python
# utils/__init__.py
from .string_utils import trim, truncate
from .date_utils import format_date
__all__ = ['trim', 'truncate', 'format_date']python
# utils/string_utils.py
def trim(text):
"""去除首尾空白"""
return text.strip()
def truncate(text, max_length=50):
"""截断长文本"""
if len(text) <= max_length:
return text
return text[:max_length - 3] + "..."python
# 主程序中使用
from utils import trim, truncate, format_date
print(trim(" hello ")) # hello
print(truncate("这是一个很长的文本内容...", 10)) # 这是一个很...虚拟环境与依赖管理
bash
# 创建虚拟环境
python -m venv myenv
# 激活(Windows PowerShell)
.\myenv\Scripts\Activate.ps1
# 激活(Linux/macOS)
# source myenv/bin/activate
# 安装依赖
pip install requests
pip install -r requirements.txt
# 导出依赖
pip freeze > requirements.txttxt
# requirements.txt 示例
requests==2.31.0
pandas==2.1.0
numpy==1.26.0练习题
题目:开发一个小工具包,实现以下功能:
- 创建一个名为
texttools的包 - 实现
word_count函数:统计文本中的中英文单词数 - 实现
extract_numbers函数:从字符串中提取所有数字 - 在
__init__.py中正确导出 - 编写使用示例
参考答案
python
# texttools/__init__.py
from .counter import word_count
from .extractor import extract_numbers
__all__ = ['word_count', 'extract_numbers']
__version__ = '1.0.0'python
# texttools/counter.py
import re
def word_count(text):
"""
统计中英文单词数
中文按字符统计(每个汉字算一个词)
英文按空格分隔统计
"""
# 提取英文单词
english_words = re.findall(r'[a-zA-Z]+', text)
# 提取中文字符(中文词语简单按字统计)
chinese_chars = re.findall(r'[\u4e00-\u9fff]', text)
return {
'english_words': len(english_words),
'chinese_chars': len(chinese_chars),
'total': len(english_words) + len(chinese_chars)
}python
# texttools/extractor.py
import re
def extract_numbers(text):
"""
从字符串中提取所有数字(整数或浮点数)
返回数字列表
"""
pattern = r'-?\d+\.?\d*'
matches = re.findall(pattern, text)
numbers = []
for m in matches:
numbers.append(float(m) if '.' in m else int(m))
return numberspython
# 使用示例
from texttools import word_count, extract_numbers
text = "Hello 你好 Python 很棒 123"
print(word_count(text))
# {'english_words': 3, 'chinese_chars': 5, 'total': 8}
numbers = extract_numbers("订单号A123,总价456.78元,折扣-10%")
print(numbers) # [123, 456.78, -10]关键思维:
- 每个模块专注一件事
__init__.py的__all__定义公开接口- 用
re模块处理复杂的文本匹配 - 合理的包结构便于复用和发布到 PyPI