0%

Python常用库介绍与使用

Python之所以成为全球最流行的编程语言之一,很大程度上得益于其丰富的标准库和强大的第三方库生态。本文将系统介绍Python常用库的功能特点和实际使用方法,帮助你快速提升Python编程技能。

标准库介绍

Python标准库是Python安装时自带的模块集合,涵盖了文件操作、网络通信、数据处理等各个领域。

1. os 模块

os模块提供了与操作系统交互的功能,包括文件和目录操作、环境变量管理等。

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

# 获取当前工作目录
print(os.getcwd())

# 创建目录
os.makedirs('new_dir/sub_dir', exist_ok=True)

# 遍历目录
for root, dirs, files in os.walk('.'):
for file in files:
print(os.path.join(root, file))

# 环境变量操作
print(os.environ.get('PATH'))

2. sys 模块

sys模块提供了访问Python解释器运行时环境的功能。

1
2
3
4
5
6
7
8
9
import sys

# 命令行参数
print(sys.argv)

# Python版本信息
print(sys.version)

# 退出程序
sys.exit(0)

3. collections 模块

collections模块提供了高性能的数据结构。

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

# Counter:计数
count = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
print(count.most_common(2))

# defaultdict:默认值字典
d = defaultdict(list)
d['key'].append(1)

# deque:双端队列
q = deque()
q.append(1)
q.appendleft(2)
q.pop()
q.popleft()

4. re 模块

re模块提供正则表达式功能。

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

# 匹配邮箱
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
email = re.search(pattern, '联系我: test@example.com')
print(email.group())

# 替换文本
text = re.sub(r'Python', 'Java', 'Python是最好的语言')

# 分割字符串
result = re.split(r'[,;]', 'a,b;c,d')

5. json 模块

json模块用于处理JSON数据。

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

# 字典转JSON
data = {'name': '张三', 'age': 25}
json_str = json.dumps(data, ensure_ascii=False, indent=2)

# JSON转字典
data = json.loads('{"name": "张三", "age": 25}')

# 读写JSON文件
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)

with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)

数据处理库

1. NumPy

NumPy是Python科学计算的基础库,提供高性能的多维数组对象和数学函数。

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

# 创建数组
arr = np.array([1, 2, 3])
matrix = np.array([[1, 2], [3, 4]])

# 数组操作
print(arr.shape)
print(arr.dtype)
print(arr.reshape(3, 1))

# 数学运算
result = arr + 2
dot_product = np.dot(matrix, matrix)

# 统计函数
print(np.mean(arr))
print(np.std(arr))

2. Pandas

Pandas是数据处理和分析的利器,提供DataFrame数据结构。

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

# 创建DataFrame
df = pd.DataFrame({
'姓名': ['张三', '李四', '王五'],
'年龄': [25, 30, 28],
'城市': ['北京', '上海', '广州']
})

# 查看数据
print(df.head())
print(df.describe())

# 数据筛选
result = df[df['年龄'] > 25]

# 读写文件
df.to_csv('data.csv', index=False, encoding='utf-8')
df = pd.read_csv('data.csv')

3. Matplotlib

Matplotlib是Python最常用的数据可视化库。

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

# 设置中文支持
plt.rcParams['font.sans-serif'] = ['SimHei']

# 绘制折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, label='sin(x)')

# 添加标签和图例
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.legend()
plt.show()

Web开发库

1. requests

requests是最流行的HTTP请求库,简洁易用。

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

# GET请求
response = requests.get('https://api.example.com/data', params={'page': 1})
print(response.status_code)
print(response.json())

# POST请求
data = {'username': 'test', 'password': '123456'}
response = requests.post('https://api.example.com/login', data=data)

# 设置请求头
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://example.com', headers=headers)

# 文件下载
response = requests.get('https://example.com/image.jpg', stream=True)
with open('image.jpg', 'wb') as f:
f.write(response.content)

2. Flask

Flask是轻量级的Web框架,适合快速构建Web应用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from flask import Flask, jsonify, request

app = Flask(__name__)

# 路由装饰器
@app.route('/')
def index():
return 'Hello, Flask!'

# JSON响应
@app.route('/api/data')
def get_data():
return jsonify({'message': 'success', 'data': []})

# POST请求
@app.route('/api/submit', methods=['POST'])
def submit():
data = request.get_json()
return jsonify({'received': data})

if __name__ == '__main__':
app.run(debug=True)

爬虫库

1. BeautifulSoup

BeautifulSoup是HTML解析库,用于从网页中提取数据。

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

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

# 查找元素
print(soup.title.string)

# 查找所有链接
for link in soup.find_all('a'):
print(link.get('href'))

机器学习库

1. Scikit-learn

Scikit-learn是Python最流行的机器学习库,提供各种经典算法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np

# 准备数据
X = np.random.rand(100, 2)
y = X[:, 0] * 2 + X[:, 1] * 3 + 1

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# 训练模型
model = LinearRegression()
model.fit(X_train, y_train)

# 预测和评估
y_pred = model.predict(X_test)
print(f'MSE: {mean_squared_error(y_test, y_pred):.2f}')

实用工具库

1. Pillow

Pillow是Python图像处理库。

1
2
3
4
5
6
7
8
9
10
11
12
from PIL import Image

# 打开图片
img = Image.open('test.jpg')

# 调整大小
img = img.resize((200, 200))

# 转换为灰度
gray_img = img.convert('L')

# 保存
gray_img.save('gray.jpg')

总结

Python的库生态非常丰富,从标准库到第三方库,几乎覆盖了所有编程领域。掌握常用库的使用是提升Python编程效率的关键。本文介绍的库只是冰山一角,还有更多优秀的库等待你去探索和学习。

-------------本文结束感谢您的阅读-------------