Python基础语法知识–常用的扩展模块

庞大的第三方模块生态系统大大增强了 Python 的多功能性。虽然 Python 的内置模块提供了坚实的基础,但非内置模块扩展了该语言的功能并使开发人员能够有效地处理各种任务。在这篇博客中,我们将探索 Python 中一些流行的非内置模块,并通过实际演示展示它们的功能。

一、Requests

Requests”模块简化了 Python 中的 HTTP 请求,使其成为网络抓取、API 集成等的首选。与内置的“urllib”模块相比,它提供了更高级别的接口,使 HTTP 交互变得优雅和直接。下面是使用 Requests 从 Web API 检索数据的快速演示:

import requests


response = requests.get('https://api.example.com/data')


data = response.json()


# Process the retrieved data

2. Beautiful Soup:

当谈到网络抓取和解析 HTML 或 XML 文档时,“Beautiful Soup”是一个广泛使用的模块。它使开发人员能够轻松地从复杂的 HTML 结构中导航和提取数据。以下是使用 Beautiful Soup 抓取和提取数据的示例:

from bs4 import BeautifulSoup


import requests


url = 'https://example.com'


response = requests.get(url)


soup = BeautifulSoup(response.content, 'html.parser')


# Extract specific elements from the HTML structure

3.Pandas:

对于数据分析和操作,“Pandas”是一个强劲的模块。它提供数据结构和函数以有效地处理大型数据集、执行计算和转换数据。让我们看一下使用 Pandas 加载 CSV 文件并执行基本数据操作的演示:

import pandas as pd


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


# Perform data manipulations, calculations, or analysis



4.Matplotlib:

如果数据可视化是您的目标,“Matplotlib”是一个多功能的绘图库。它提供了广泛的图表、自定义选项和样式来创建有影响力的数据可视化表明。让我们使用 Matplotlib 绘制一个简单的折线图:

import matplotlib.pyplot as plt


x = [1, 2, 3, 4, 5]


y = [2, 4, 6, 8, 10]


plt.plot(x, y)


plt.xlabel('X-axis')


plt.ylabel('Y-axis')


plt.title('Simple Line Graph')


plt.show()

5. NumPy:

“NumPy”是 Python 科学计算的基础包。它提供了强劲的多维数组、数学函数和数组操作工具。下面是使用 NumPy 创建和操作数组的示例:

import numpy as np


# Create a 2D array


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


# Perform operations on the array

6.Pip

“Pip” 是管理 Python 包和简化依赖管理不可或缺的工具。在 Python 生态系统中,使用“pip”可以毫不费力地管理外部包和依赖项。Python 3.4之后作为 Python 默认的包安装器,pip 允许开发者方便地下载、安装、升级和管理第三方库。例如:

pip install package_name


pip install package_name==version_number


pip install --upgrade package_name


pip list


pip uninstall package_name


pip freeze > requirements.txt



7.PyYAML

PyYAML 是一个流行的 Python 库,它允许您使用 YAML(YAML 不是标记语言)文件。它提供了一种方便的方法来解析 YAML 文档,从中提取数据,并将 Python 对象序列化为 YAML 格式。

1).PyYAML 提供了将 YAML 文件加载和解析为 Python 对象的方法。下面是从 YAML 文件加载和访问数据的示例:

import yaml


# Load the YAML file


with open('data.yaml', 'r') as file:


  data = yaml.load(file, Loader=yaml.FullLoader)


# Access the data


print(data['key'])

2).PyYAML 还使您能够将 Python 对象序列化为 YAML 格式。这对于存储配置数据或在不同系统之间传输数据很有用。下面是将 Python 字典序列化为 YAML 文件的示例:

import yaml


# Python object to serialize


data = {'key': 'value'}


# Serialize to YAML


with open('output.yaml', 'w') as file:


  yaml.dump(data, file)



8.RSA

RSA(Rivest-Shamir-Adleman)算法是一种广泛使用的加密和解密技术,用于保护数据传输和存储。在 Python 中,RSA 模块提供了生成 RSA 密钥对、加密和解密数据以及签署和验证数字签名的功能。

1).RSA 模块允许您生成 RSA 密钥对,包括用于加密的公钥和用于解密的私钥。以下是生成 RSA 密钥对的示例:

from Crypto.PublicKey import RSA


# Generate a new RSA key pair


key = RSA.generate(2048)


# Extract the public and private keys


public_key = key.publickey().export_key()


private_key = key.export_key()


# Save the keys to files


with open('public_key.pem', 'wb') as file:


  file.write(public_key)


with open('private_key.pem', 'wb') as file:


  file.write(private_key)

2).使用 RSA 密钥对,您可以使用接收方的公钥加密数据并使用私钥解密数据。这是一个例子:

from Crypto.PublicKey import RSA


from Crypto.Cipher import PKCS1_OAEP


# Load the recipient's public key


with open('public_key.pem', 'rb') as file:


  recipient_public_key = RSA.import_key(file.read())


# Encrypt data using the recipient's public key


cipher_rsa = PKCS1_OAEP.new(recipient_public_key)


encrypted_data = cipher_rsa.encrypt(b'Secret message')


# Load the private key for decryption


with open('private_key.pem', 'rb') as file:


  private_key = RSA.import_key(file.read())


# Decrypt the encrypted data using the private key


cipher_rsa = PKCS1_OAEP.new(private_key)


decrypted_data = cipher_rsa.decrypt(encrypted_data)


print(decrypted_data.decode())

3). RSA 模块还支持数字签名,使您可以验证数据的完整性和真实性。下面是签署和验证数字签名的示例:

from Crypto.Signature import pkcs1_15


from Crypto.Hash import SHA256


# Load the private key for signing


with open('private_key.pem', 'rb') as file:


  private_key = RSA.import_key(file.read())


# Sign a message using the private key


message = b'Secret message'


hash = SHA256.new(message)


signature = pkcs1_15.new(private_key).sign(hash)


# Load the public key for verification


with open('public_key.pem', 'rb') as file:


  public_key = RSA.import_key(file.read())


# Verify the signature using the public key


hash = SHA256.new(message)


try:


  pkcs1_15.new(public_key).verify(hash, signature)
  
  print('Signature is valid.')


except (ValueError, TypeError):


  print('Signature is invalid.')

Python 的非内置模块显著地扩展了该语言的功能并迎合了各种领域。在这篇博客中,我们探索了一些流行的模块,包括用于 HTTP 交互的 Requests、用于网络抓取的 Beautiful Soup、用于数据分析的 Pandas、用于数据可视化的 Matplotlib 以及用于科学计算的 NumPy等。通过利用这些模块,您可以简化您的开发过程、提高生产力并在您的 Pythonic 之旅中开启新的可能性。因此,继续探索这些模块,并在您的项目中利用它们的力量!

© 版权声明

相关文章

暂无评论

none
暂无评论...