Python案例如何用第三方库

wen python案例 53

本文目录导读:

Python案例如何用第三方库

  1. 第三方库安装方法
  2. 常用第三方库案例
  3. 综合应用案例
  4. 依赖管理

我来为你介绍Python使用第三方库的各种案例和方法。

第三方库安装方法

使用pip安装

# 安装最新版本
pip install 库名
# 安装指定版本
pip install 库名==1.2.3
# 安装多个库
pip install requests pandas numpy
# 从requirements.txt安装
pip install -r requirements.txt

国内镜像加速

# 使用清华镜像
pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 使用阿里云镜像
pip install 库名 -i https://mirrors.aliyun.com/pypi/simple/

常用第三方库案例

Requests - HTTP请求库

import requests
# GET请求
response = requests.get('https://api.github.com')
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.json()}")
# POST请求
data = {'username': 'test', 'password': '123456'}
response = requests.post('https://httpbin.org/post', json=data)
print(response.json())
# 带参数请求
params = {'q': 'python', 'page': 1}
response = requests.get('https://api.github.com/search/repositories', params=params)
print(f"搜索结果: {len(response.json()['items'])} 个")

BeautifulSoup - 网页解析

from bs4 import BeautifulSoup
import requests
# 获取网页内容
url = 'https://books.toscrape.com/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取所有书名
books = soup.find_all('h3')
for book in books[:5]:= book.find('a')['title']
    print(f"书名: {title}")
# 提取所有价格
prices = soup.find_all('p', class_='price_color')
for price in prices[:5]:
    print(f"价格: {price.text}")

Pandas - 数据处理

import pandas as pd
import numpy as np
# 创建DataFrame
data = {
    '姓名': ['张三', '李四', '王五'],
    '年龄': [25, 30, 35],
    '城市': ['北京', '上海', '广州'],
    '工资': [8000, 12000, 15000]
}
df = pd.DataFrame(data)
print(df)
# 读取CSV文件
# df = pd.read_csv('data.csv')
# 数据筛选
young_people = df[df['年龄'] < 30]
print("\n年龄小于30的人:")
print(young_people)
# 数据统计
print("\n工资统计:")
print(df['工资'].describe())
# 分组统计
city_avg = df.groupby('城市')['工资'].mean()
print("\n各城市平均工资:")
print(city_avg)

Matplotlib - 数据可视化

import matplotlib.pyplot as plt
import numpy as np
# 数据
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 18, 20]
# 创建折线图
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2, label='销售额')
plt.scatter(x, y, color='red', s=50)
# 添加标签和标题
plt.xlabel('月份')
plt.ylabel('销售额 (万元)')'月度销售趋势图')
plt.legend()
# 添加网格
plt.grid(True, alpha=0.3)
# 显示图形
plt.show()
# 创建柱状图
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
plt.figure(figsize=(8, 5))
plt.bar(categories, values, color=['blue', 'green', 'red', 'orange'])'各品类销售对比')
plt.show()

NumPy - 数值计算

import numpy as np
# 创建数组
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([6, 7, 8, 9, 10])
# 数组运算
print(f"数组相加: {arr1 + arr2}")
print(f"数组相乘: {arr1 * arr2}")
print(f"数组均值: {arr1.mean()}")
print(f"数组标准差: {arr1.std()}")
# 矩阵运算
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
print(f"\n矩阵乘法:\n{np.dot(matrix1, matrix2)}")
print(f"\n矩阵转置:\n{matrix1.T}")
# 随机数生成
random_data = np.random.randn(100)
print(f"\n随机数据统计:")
print(f"均值: {random_data.mean():.2f}")
print(f"标准差: {random_data.std():.2f}")

Pillow - 图像处理

from PIL import Image, ImageFilter, ImageEnhance
# 打开图像
img = Image.open('example.jpg')
# 图像基本信息
print(f"图像大小: {img.size}")
print(f"图像格式: {img.format}")
print(f"图像模式: {img.mode}")
# 图像处理
# 调整大小
resized_img = img.resize((200, 200))
# 旋转
rotated_img = img.rotate(45)
# 滤镜效果
blurred_img = img.filter(ImageFilter.BLUR)
# 增强亮度
enhancer = ImageEnhance.Brightness(img)
bright_img = enhancer.enhance(1.5)
# 保存处理后的图像
# resized_img.save('resized.jpg')
# rotated_img.save('rotated.jpg')

综合应用案例

网络爬虫示例

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
def crawl_books():
    """爬取豆瓣电影Top250"""
    movies = []
    for start in range(0, 250, 25):
        url = f'https://movie.douban.com/top250?start={start}'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        try:
            response = requests.get(url, headers=headers)
            soup = BeautifulSoup(response.text, 'html.parser')
            for item in soup.find_all('div', class_='item'):
                title = item.find('span', class_='title').text
                rating = item.find('span', class_='rating_num').text
                movies.append({'电影名称': title, '评分': rating})
            print(f"已获取 {len(movies)} 部电影信息")
            time.sleep(1)  # 避免请求过快
        except Exception as e:
            print(f"请求失败: {e}")
    # 保存到Excel
    df = pd.DataFrame(movies)
    df.to_excel('豆瓣电影Top250.xlsx', index=False)
    print("数据已保存到Excel文件")
# 运行爬虫
crawl_books()

数据分析可视化

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def analyze_sales_data():
    """分析销售数据"""
    # 生成模拟数据
    np.random.seed(42)
    dates = pd.date_range('2024-01-01', periods=100, freq='D')
    sales_data = pd.DataFrame({
        '日期': dates,
        '销售额': np.random.randint(1000, 5000, 100),
        '订单数': np.random.randint(50, 200, 100),
        '品类': np.random.choice(['电子产品', '服装', '食品', '家居'], 100)
    })
    # 统计分析
    print("=== 基本统计信息 ===")
    print(sales_data.describe())
    print(f"\n=== 各品类销售额 ===")
    category_sales = sales_data.groupby('品类')['销售额'].sum()
    print(category_sales)
    # 可视化
    fig, axes = plt.subplots(2, 2, figsize=(15, 10))
    # 1. 销售额趋势
    axes[0, 0].plot(sales_data['日期'], sales_data['销售额'], 'b-')
    axes[0, 0].set_title('每日销售额趋势')
    axes[0, 0].set_xlabel('日期')
    axes[0, 0].set_ylabel('销售额')
    # 2. 订单数分布
    axes[0, 1].hist(sales_data['订单数'], bins=20, color='green', alpha=0.7)
    axes[0, 1].set_title('订单数分布')
    axes[0, 1].set_xlabel('订单数')
    axes[0, 1].set_ylabel('频次')
    # 3. 品类销售额饼图
    axes[1, 0].pie(category_sales.values, labels=category_sales.index, autopct='%1.1f%%')
    axes[1, 0].set_title('各品类销售额占比')
    # 4. 销售额与订单数关系
    axes[1, 1].scatter(sales_data['订单数'], sales_data['销售额'], alpha=0.6)
    axes[1, 1].set_title('销售额与订单数关系')
    axes[1, 1].set_xlabel('订单数')
    axes[1, 1].set_ylabel('销售额')
    plt.tight_layout()
    plt.show()
# 运行分析
analyze_sales_data()

依赖管理

创建requirements.txt

# 生成当前环境依赖
pip freeze > requirements.txt

使用虚拟环境

# 创建虚拟环境
python -m venv myenv
# 激活虚拟环境
# Windows:
myenv\Scripts\activate
# Mac/Linux:
source myenv/bin/activate
# 安装依赖
pip install -r requirements.txt

这些案例涵盖了Python第三方库的主要应用场景,你可以根据实际需求选择合适的库进行学习和使用,关键在于理解库的功能和用途,而不是死记硬背代码。

抱歉,评论功能暂时关闭!