百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

python的常用库及示例

ztj100 2025-01-16 21:40 31 浏览 0 评论

Python拥有丰富的库生态系统,涵盖了从数据分析到web开发的各个领域。以下是一些最常用和最重要的Python库,我会对每个库进行详细说明并提供使用示例。


1. NumPy (Numerical Python)


NumPy是Python科学计算的基础库,提供了高性能的多维数组对象和用于处理这些数组的工具。


主要特点:

- 强大的N维数组对象

- 复杂的广播功能

- 用于整合C/C++和Fortran代码的工具

- 有用的线性代数、傅里叶变换和随机数生成功能


示例:


```python

import numpy as np


# 创建数组

arr = np.array([1, 2, 3, 4, 5])


# 数学运算

print(np.mean(arr)) # 平均值

print(np.std(arr)) # 标准差


# 创建二维数组

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])


# 矩阵运算

print(np.transpose(matrix)) # 转置

print(np.linalg.inv(matrix)) # 求逆(如果可逆)


# 生成随机数

random_arr = np.random.rand(5, 5) # 5x5的随机数组


# 数组操作

reshaped = arr.reshape(5, 1) # 重塑数组形状

```


2. Pandas


Pandas是用于数据操作和分析的库。它提供了数据结构和操作工具,使处理结构化数据变得快速、灵活且富有表现力。


主要特点:

- DataFrame对象用于处理二维表格数据

- Series对象用于一维标记数组

- 处理各种文件格式(CSV、Excel、SQL数据库等)的工具

- 数据对齐和集成处理缺失数据

- 数据集的合并和连接

- 时间序列功能


示例:


```python

import pandas as pd


# 创建DataFrame

df = pd.DataFrame({

'Name': ['John', 'Anna', 'Peter', 'Linda'],

'Age': [28, 34, 29, 32],

'City': ['New York', 'Paris', 'Berlin', 'London']

})


# 基本操作

print(df.head()) # 查看前几行

print(df.describe()) # 基本统计描述


# 选择和过滤

print(df['Name']) # 选择单列

print(df[df['Age'] > 30]) # 过滤


# 添加新列

df['Country'] = ['USA', 'France', 'Germany', 'UK']


# 分组和聚合

print(df.groupby('Country')['Age'].mean())


# 读取CSV文件

# df = pd.read_csv('data.csv')


# 写入Excel文件

# df.to_excel('output.xlsx', index=False)

```


3. Matplotlib


Matplotlib是一个绘图库,用于创建静态、动画和交互式可视化。


主要特点:

- 创建高质量的图表(折线图、散点图、柱状图等)

- 可自定义的图表样式和布局

- 支持多种输出格式(PNG、PDF、SVG、动画GIF等)

- 3D图表支持


示例:


```python

import matplotlib.pyplot as plt

import numpy as np


# 创建数据

x = np.linspace(0, 2 * np.pi, 100)

y = np.sin(x)


# 创建图表

plt.figure(figsize=(10, 6))

plt.plot(x, y, label='sin(x)')

plt.title('Sine Wave')

plt.xlabel('x')

plt.ylabel('y')

plt.legend()

plt.grid(True)


# 显示图表

plt.show()


# 创建子图

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))


ax1.plot(x, np.sin(x), 'b-', label='sin(x)')

ax1.set_title('Sine')


ax2.plot(x, np.cos(x), 'r-', label='cos(x)')

ax2.set_title('Cosine')


for ax in (ax1, ax2):

ax.legend()

ax.grid(True)


plt.tight_layout()

plt.show()

```


4. Scikit-learn


Scikit-learn是机器学习领域最受欢迎的Python库之一,提供了各种监督和无监督学习算法。


主要特点:

- 分类、回归、聚类算法

- 模型选择和评估工具

- 数据预处理和特征选择工具

- 集成方法


示例:


```python

from sklearn import datasets, model_selection, svm, metrics

import matplotlib.pyplot as plt


# 加载数据

iris = datasets.load_iris()

X = iris.data

y = iris.target


# 分割数据集

X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3, random_state=42)


# 创建和训练模型

model = svm.SVC(kernel='linear')

model.fit(X_train, y_train)


# 预测

y_pred = model.predict(X_test)


# 评估模型

print("Accuracy:", metrics.accuracy_score(y_test, y_pred))

print("\nClassification Report:\n", metrics.classification_report(y_test, y_pred))


# 可视化结果(仅使用前两个特征)

plt.figure(figsize=(10, 6))

plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred, cmap=plt.cm.Set1)

plt.title('SVM Classification Results')

plt.xlabel('Sepal length')

plt.ylabel('Sepal width')

plt.show()

```


5. TensorFlow 和 PyTorch


这两个库都是用于深度学习的强大工具。TensorFlow由Google开发,而PyTorch由Facebook开发。


主要特点:

- 构建和训练神经网络

- 自动微分功能

- GPU加速支持

- 丰富的预训练模型和工具


TensorFlow示例:


```python

import tensorflow as tf

from tensorflow.keras import layers, models


# 创建一个简单的神经网络

model = models.Sequential([

layers.Dense(64, activation='relu', input_shape=(784,)),

layers.Dense(64, activation='relu'),

layers.Dense(10, activation='softmax')

])


# 编译模型

model.compile(optimizer='adam',

loss='sparse_categorical_crossentropy',

metrics=['accuracy'])


# 假设我们有训练数据 x_train 和 y_train

# model.fit(x_train, y_train, epochs=5)


# 假设我们有测试数据 x_test

# predictions = model.predict(x_test)

```


PyTorch示例:


```python

import torch

import torch.nn as nn

import torch.optim as optim


# 定义一个简单的神经网络

class SimpleNet(nn.Module):

def __init__(self):

super(SimpleNet, self).__init__()

self.fc1 = nn.Linear(784, 64)

self.fc2 = nn.Linear(64, 64)

self.fc3 = nn.Linear(64, 10)


def forward(self, x):

x = torch.relu(self.fc1(x))

x = torch.relu(self.fc2(x))

x = self.fc3(x)

return x


# 创建模型实例

model = SimpleNet()


# 定义损失函数和优化器

criterion = nn.CrossEntropyLoss()

optimizer = optim.Adam(model.parameters())


# 训练循环(假设我们有训练数据)

# for epoch in range(5):

# for data, target in train_loader:

# optimizer.zero_grad()

# output = model(data)

# loss = criterion(output, target)

# loss.backward()

# optimizer.step()

```


6. Requests


Requests是一个简单而优雅的HTTP库,广泛用于发送HTTP/1.1请求。


主要特点:

- 简单的API设计

- 自动解码内容

- 会话和Cookie持久性

- 内置的身份验证支持


示例:


```python

import requests


# 发送GET请求

response = requests.get('https://api.github.com/user', auth=('user', 'pass'))

print(response.status_code)

print(response.headers['content-type'])

print(response.json())


# 发送POST请求

data = {'key': 'value'}

response = requests.post('https://httpbin.org/post', data=data)

print(response.text)


# 使用会话

with requests.Session() as session:

session.auth = ('user', 'pass')

response = session.get('https://api.github.com/user')

print(response.json())


# 处理异常

try:

response = requests.get('https://api.github.com/invalid', timeout=3)

response.raise_for_status()

except requests.exceptions.HTTPError as err:

print(f"HTTP error occurred: {err}")

except requests.exceptions.RequestException as err:

print(f"An error occurred: {err}")

```


7. Flask


Flask是一个轻量级的Web应用框架。它被设计为简单、灵活,并且可以快速开始开发。


主要特点:

- 内置开发服务器和调试器

- RESTful请求分发

- 模板支持(Jinja2)

- 安全的客户端会话

- 支持单元测试

- 与WSGI 1.0兼容


示例:


```python

from flask import Flask, request, jsonify


app = Flask(__name__)


@app.route('/')

def hello_world():

return 'Hello, World!'


@app.route('/user/<username>')

def show_user_profile(username):

return f'User {username}'


@app.route('/post/<int:post_id>')

def show_post(post_id):

return f'Post {post_id}'


@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

return do_the_login()

else:

return show_the_login_form()


@app.route('/api/data')

def get_data():

data = {'name': 'John', 'age': 30}

return jsonify(data)


if __name__ == '__main__':

app.run(debug=True)

```


8. Django


Django是一个高级Python Web框架,鼓励快速开发和干净、实用的设计。


主要特点:

- ORM(对象关系映射)

- URL路由

- 模板引擎

- 表单处理

- 身份验证系统

- 管理界面


示例(项目结构):


```

myproject/

manage.py

myproject/

__init__.py

settings.py

urls.py

wsgi.py

myapp/

__init__.py

admin.py

apps.py

models.py

tests.py

views.py

urls.py

```


models.py:

```python

from django.db import models


class Question(models.Model):

question_text = models.CharField(max_length=200)

pub_date = models.DateTimeField('date published')


class Choice(models.Model):

question = models.ForeignKey(Question, on_delete=models.CASCADE)

choice_text = models.CharField(max_length=200)

votes = models.IntegerField(default=0)

```


views.py:

```python

from django.http import HttpResponse

from django.shortcuts import render

from .models import Question


def index(request):

latest_question_list = Question.objects.order_by('-pub_date')[:5]

context = {'latest_question_list': latest_question_list}

return render(request, 'polls/index.html', context)


def detail(request, question_id):

question = get_object_or_404(Question, pk=question_id)

return render(request, 'polls/detail.html', {'question': question})

```


urls.py:

```python

from django.urls import path

from . import views


urlpatterns = [

path('', views.index, name='index'),

path('<int:question_id>/', views.detail, name='detail'),

]

```


9. Selenium


Selenium是一个用于Web应用程序测试的工具。它直接驱动浏览器,模拟用户的操作。


主要特点:

- 支持多种浏览器(Chrome、Firefox、Safari等)

- 可以自动化浏览器操作

- 支持多种编程语言(Python、Java、C#等)

- 可以截图

- 支持等待和超时机制


示例:


```python

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC


# 初始化驱动

driver = webdriver.Chrome() # 确保你有ChromeDriver并在PATH中


try:

# 打开网页

driver.get("http://www.python.org")


# 查找元素

search_bar = driver.find_element(By.NAME, "q")

search_bar.clear()

search_bar.send_keys("pycon")

search_bar.send_keys(Keys.RETURN)


# 等待结果加载

WebDriverWait(driver, 10).until(

EC.presence_of_element_located((By.CLASS_NAME, "list-recent-events"))

)


# 找到结果

results = driver.find_elements(By.CSS_SELECTOR, ".list-recent-events li")

for result in results:

print(result.text)


finally:

driver.quit() # 关闭浏览器

```


10. Beautiful Soup


Beautiful Soup是一个用于从HTML和XML文件中提取数据的库。它与您喜欢的解析器一起工作,提供惯用的方法来浏览、搜索和修改解析树。


主要特点:

- 简单的API

- 支持多种解析器

- 强大的搜索和导航功能

- 自动编码检测


示例:


```python

from bs4 import BeautifulSoup

import requests


# 获取网页内容

url = "http://www.python.org"

response = requests.get(url)

html_content = response.

相关推荐

30天学会Python编程:16. Python常用标准库使用教程

16.1collections模块16.1.1高级数据结构16.1.2示例...

强烈推荐!Python 这个宝藏库 re 正则匹配

Python的re模块(RegularExpression正则表达式)提供各种正则表达式的匹配操作。...

Python爬虫中正则表达式的用法,只讲如何应用,不讲原理

Python爬虫:正则的用法(非原理)。大家好,这节课给大家讲正则的实际用法,不讲原理,通俗易懂的讲如何用正则抓取内容。·导入re库,这里是需要从html这段字符串中提取出中间的那几个文字。实例一个对...

Python数据分析实战-正则提取文本的URL网址和邮箱(源码和效果)

实现功能:Python数据分析实战-利用正则表达式提取文本中的URL网址和邮箱...

python爬虫教程之爬取当当网 Top 500 本五星好评书籍

我们使用requests和re来写一个爬虫作为一个爱看书的你(说的跟真的似的)怎么能发现好书呢?所以我们爬取当当网的前500本好五星评书籍怎么样?ok接下来就是学习python的正确姿...

深入理解re模块:Python中的正则表达式神器解析

在Python中,"re"是一个强大的模块,用于处理正则表达式(regularexpressions)。正则表达式是一种强大的文本模式匹配工具,用于在字符串中查找、替换或提取特定模式...

如何使用正则表达式和 Python 匹配不以模式开头的字符串

需要在Python中使用正则表达式来匹配不以给定模式开头的字符串吗?如果是这样,你可以使用下面的语法来查找所有的字符串,除了那些不以https开始的字符串。r"^(?!https).*&...

先Mark后用!8分钟读懂 Python 性能优化

从本文总结了Python开发时,遇到的性能优化问题的定位和解决。概述:性能优化的原则——优化需要优化的部分。性能优化的一般步骤:首先,让你的程序跑起来结果一切正常。然后,运行这个结果正常的代码,看看它...

Python“三步”即可爬取,毋庸置疑

声明:本实例仅供学习,切忌遵守robots协议,请不要使用多线程等方式频繁访问网站。#第一步导入模块importreimportrequests#第二步获取你想爬取的网页地址,发送请求,获取网页内...

简单学Python——re库(正则表达式)2(split、findall、和sub)

1、split():分割字符串,返回列表语法:re.split('分隔符','目标字符串')例如:importrere.split(',','...

Lavazza拉瓦萨再度牵手上海大师赛

阅读此文前,麻烦您点击一下“关注”,方便您进行讨论和分享。Lavazza拉瓦萨再度牵手上海大师赛标题:2024上海大师赛:网球与咖啡的浪漫邂逅在2024年的上海劳力士大师赛上,拉瓦萨咖啡再次成为官...

ArkUI-X构建Android平台AAR及使用

本教程主要讲述如何利用ArkUI-XSDK完成AndroidAAR开发,实现基于ArkTS的声明式开发范式在android平台显示。包括:1.跨平台Library工程开发介绍...

Deepseek写歌详细教程(怎样用deepseek写歌功能)

以下为结合DeepSeek及相关工具实现AI写歌的详细教程,涵盖作词、作曲、演唱全流程:一、核心流程三步法1.AI生成歌词-打开DeepSeek(网页/APP/API),使用结构化提示词生成歌词:...

“AI说唱解说影视”走红,“零基础入行”靠谱吗?本报记者实测

“手里翻找冻鱼,精心的布局;老漠却不言语,脸上带笑意……”《狂飙》剧情被写成歌词,再配上“科目三”背景音乐的演唱,这段1分钟30秒的视频受到了无数网友的点赞。最近一段时间随着AI技术的发展,说唱解说影...

AI音乐制作神器揭秘!3款工具让你秒变高手

在音乐创作的领域里,每个人都有一颗想要成为大师的心。但是面对复杂的乐理知识和繁复的制作过程,许多人的热情被一点点消磨。...

取消回复欢迎 发表评论: