Python语法及常用用法(5)

Python语法及常用用法(5)

文章目录

111. 使用 SQLAlchemy 进行数据库操作:

# 使用 SQLAlchemy 进行数据库操作
# 安装 SQLAlchemy:pip install SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String, MetaData
from sqlalchemy.orm import declarative_base, Session

# 创建数据库引擎
engine = create_engine("sqlite:///example.db")

# 创建数据模型
Base = declarative_base()

class Person(Base):
    __tablename__ = "people"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    age = Column(Integer)

# 创建表格
Base.metadata.create_all(bind=engine)

# 创建数据库会话
session = Session(engine)

# 插入数据
person = Person(name="Bob", age=25)
session.add(person)
session.commit()

# 查询数据
people = session.query(Person).all()
for p in people:
    print(f"ID: {p.id}, Name: {p.name}, Age: {p.age}")

112. 使用 pandas-profiling 生成数据分析报告:

# 使用 pandas-profiling 生成数据分析报告
# 安装 pandas-profiling:pip install pandas-profiling
import pandas as pd
from pandas_profiling import ProfileReport

# 读取数据
data = pd.read_csv("example.csv")

# 生成数据分析报告
profile = ProfileReport(data)

# 将报告保存为 HTML 文件
profile.to_file("data_analysis_report.html")

113. 使用 docker 容器化应用:

# 使用 docker 容器化应用
# 创建 Dockerfile

# 使用官方 Python 镜像作为基础镜像
FROM python:3.8-slim

# 设置工作目录
WORKDIR /app

# 复制应用代码到工作目录
COPY . .

# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt

# 启动应用
CMD ["python", "app.py"]

114. 使用 hug 快速创建 Web API:

# 使用 hug 快速创建 Web API
# 安装 hug:pip install hug
import hug

# 定义 API 路由
@hug.get("/")
def hello():
    return {"message": "Hello, Hug!"}

115. 使用 openpyxl 处理 Excel 文件:

# 使用 openpyxl 处理 Excel 文件
# 安装 openpyxl:pip install openpyxl
import openpyxl

# 创建工作簿和工作表
workbook = openpyxl.Workbook()
sheet = workbook.active

# 写入数据
sheet["A1"] = "Hello"
sheet["B1"] = "World"

# 保存工作簿
workbook.save("example.xlsx")

116. 使用 python-docx 处理 Word 文档:

# 使用 python-docx 处理 Word 文档
# 安装 python-docx:pip install python-docx
from docx import Document

# 创建文档
doc = Document()

# 添加段落和文本
doc.add_paragraph("Hello, Python!")
doc.add_paragraph("This is a Word document.")

# 保存文档
doc.save("example.docx")

117. 使用 pyinstaller 将 Python 脚本打包成可执行文件:

# 使用 pyinstaller 将 Python 脚本打包成可执行文件
# 安装 pyinstaller:pip install pyinstaller

# 打包脚本
# pyinstaller myscript.py

118. 使用 youtube_dl 下载 YouTube 视频:

# 使用 youtube_dl 下载 YouTube 视频
# 安装 youtube_dl:pip install youtube_dl
import youtube_dl

# 指定下载选项
options = {
    'format': 'bestvideo+bestaudio/best',
    'outtmpl': 'downloads/%(title)s.%(ext)s',
}

# 视频链接
video_url = 'https://www.youtube.com/watch?v=example'

# 创建下载器
with youtube_dl.YoutubeDL(options) as ydl:
    ydl.download([video_url])

119. 使用 regex 模块进行高级正则表达式操作:

# 使用 regex 模块进行高级正则表达式操作
# 安装 regex:pip install regex
import regex

# 匹配邮箱地址
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
text = 'Emails: alice@example.com, bob@gmail.com'

matches = regex.findall(pattern, text)
print(matches)

120. 使用 pytz 处理时区:

# 使用 pytz 处理时区
from datetime import datetime
import pytz

# 获取当前时间
local_time = datetime.now()
print("Local Time:", local_time)

# 设置时区
tz = pytz.timezone('America/New_York')
new_york_time = local_time.astimezone(tz)
print("New York Time:", new_york_time)

121. 使用 selenium 进行 Web 自动化测试:

# 使用 selenium 进行 Web 自动化测试
# 安装 selenium:pip install selenium
from selenium import webdriver

# 创建浏览器驱动
driver = webdriver.Chrome()

# 打开网页
driver.get("https://www.example.com")

# 查找元素并操作
element = driver.find_element_by_name("q")
element.send_keys("Python")
element.submit()

# 关闭浏览器
driver.quit()

122. 使用 itertools 进行迭代操作:

# 使用 itertools 进行迭代操作
import itertools

# 生成无限序列
count = itertools.count(start=1, step=2)

# 获取前 5 个元素
for _ in range(5):
    print(next(count))

123. 使用 Faker 生成虚拟数据:

# 使用 Faker 生成虚拟数据
# 安装 Faker:pip install Faker
from faker import Faker

# 创建虚拟数据生成器
fake = Faker()

# 生成姓名、地址等虚拟数据
name = fake.name()
address = fake.address()

print("Name:", name)
print("Address:", address)

124. 使用 tqdm 创建进度条:

# 使用 tqdm 创建进度条
# 安装 tqdm:pip install tqdm
from tqdm import tqdm
import time

# 模拟任务
for _ in tqdm(range(10), desc="Processing"):
    time.sleep(0.1)

125. 使用 PyQt 创建桌面应用程序:

# 使用 PyQt 创建桌面应用程序
# 安装 PyQt:pip install PyQt5
from PyQt5.QtWidgets import QApplication, QLabel

# 创建应用程序
app = QApplication([])

# 创建窗口和标签
window = QLabel("Hello, PyQt!")
window.show()

# 运行应用程序
app.exec_()

126. 使用 fastapiuvicorn 创建异步 Web API:

# 使用 fastapi 和 uvicorn 创建异步 Web API
# 安装 fastapi:pip install fastapi
# 安装 uvicorn:pip install uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, FastAPI!"}

127. 使用 beautifulsoup4 进行网页解析:

# 使用 beautifulsoup4 进行网页解析
# 安装 beautifulsoup4:pip install beautifulsoup4
from bs4 import BeautifulSoup
import requests

# 获取网页内容
url = 'https://www.example.com'
response = requests.get(url)
html_content = response.text

# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html_content, 'html.parser')

# 提取标题
title = soup.title.string
print("Title:", title)

128. 使用 paramiko 进行SSH操作:

# 使用 paramiko 进行SSH操作
# 安装 paramiko:pip install paramiko
import paramiko

# 创建SSH客户端
ssh = paramiko.SSHClient()

# 连接到远程服务器
ssh.connect('example.com', username='your_username', password='your_password')

# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.read().decode())

# 关闭SSH连接
ssh.close()

129. 使用 pandas 进行数据清理和转换:

# 使用 pandas 进行数据清理和转换
import pandas as pd

# 读取数据
data = pd.read_csv('example.csv')

# 查看前几行数据
print(data.head())

# 进行数据清理和转换
cleaned_data = data.dropna()
transformed_data = cleaned_data['column1'] * 2

# 将处理后的数据保存为新文件
transformed_data.to_csv('transformed_data.csv', index=False)

130. 使用 plotly 创建交互式图表:

# 使用 plotly 创建交互式图表
# 安装 plotly:pip install plotly
import plotly.express as px

# 创建数据
data = px.data.iris()

# 创建散点图
scatter_plot = px.scatter(data, x='sepal_width', y='sepal_length', color='species', size='petal_length')

# 显示图表
scatter_plot.show()

131. 使用 networkx 分析图结构:

# 使用 networkx 分析图结构
# 安装 networkx:pip install networkx
import networkx as nx
import matplotlib.pyplot as plt

# 创建图
G = nx.Graph()

# 添加节点和边
G.add_nodes_from([1, 2, 3])
G.add_edges_from([(1, 2), (2, 3), (3, 1)])

# 绘制图形
nx.draw(G, with_labels=True)
plt.show()

132. 使用 h5py 处理HDF5文件:

# 使用 h5py 处理HDF5文件
# 安装 h5py:pip install h5py
import h5py

# 创建HDF5文件
with h5py.File('example.h5', 'w') as file:
    # 创建数据集
    dataset = file.create_dataset('my_dataset', data=[1, 2, 3])

    # 读取数据集
    print(dataset[:])

133. 使用 PyQt 创建自定义对话框:

# 使用 PyQt 创建自定义对话框
# 安装 PyQt:pip install PyQt5
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QPushButton

class CustomDialog(QDialog):
    def __init__(self):
        super().__init__()

        # 创建布局和按钮
        layout = QVBoxLayout()
        button = QPushButton("Click me!")
        button.clicked.connect(self.show_message)
        layout.addWidget(button)

        # 设置对话框布局
        self.setLayout(layout)

    def show_message(self):
        print("Button clicked!")

# 创建应用程序
app = QApplication([])

# 创建自定义对话框并显示
dialog = CustomDialog()
dialog.exec_()

134. 使用 imghdr 模块检测图像文件类型:

# 使用 imghdr 模块检测图像文件类型
import imghdr

# 图像文件路径
image_path = 'example.jpg'

# 检测图像文件类型
image_type = imghdr.what(image_path)

print("Image Type:", image_type)

135. 使用 jsonpickle 序列化/反序列化复杂对象:

# 使用 jsonpickle 序列化/反序列化复杂对象
# 安装 jsonpickle:pip install jsonpickle
import jsonpickle

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 创建对象
person = Person("Alice", 30)

# 对象序列化为 JSON 字符串
json_str = jsonpickle.encode(person)
print(json_str)

# JSON 字符串反序列化为对象
decoded_person = jsonpickle.decode(json_str)
print(decoded_person.name, decoded_person.age)

136. 使用 sqlite3 模块进行SQLite数据库操作:

# 使用 sqlite3 模块进行SQLite数据库操作
import sqlite3

# 连接到SQLite数据库(如果不存在则创建)
conn = sqlite3.connect('example.db')

# 创建游标对象
cursor = conn.cursor()

# 创建表格
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        age INTEGER
    )
''')

# 插入数据
cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 25))

# 提交事务
conn.commit()

# 查询数据
cursor.execute('SELECT * FROM users')
print(cursor.fetchall())

# 关闭连接
conn.close()

137. 使用 pyautogui 进行鼠标和键盘自动化:

# 使用 pyautogui 进行鼠标和键盘自动化
# 安装 pyautogui:pip install pyautogui
import pyautogui
import time

# 移动鼠标到指定位置
pyautogui.moveTo(100, 100, duration=1)

# 模拟点击
pyautogui.click()

# 模拟键盘输入
pyautogui.typewrite('Hello, PyAutoGUI!')

# 等待一秒
time.sleep(1)

# 截屏
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')

138. 使用 boto3 连接Amazon S3存储:

# 使用 boto3 连接Amazon S3存储
# 安装 boto3:pip install boto3
import boto3

# 配置AWS密钥和区域
aws_access_key = 'your_access_key'
aws_secret_key = 'your_secret_key'
region = 'your_region'

# 创建S3客户端
s3 = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, region_name=region)

# 上传文件到S3桶
bucket_name = 'your_bucket_name'
file_path = 'example.txt'
object_key = 'example.txt'

s3.upload_file(file_path, bucket_name, object_key)

139. 使用 Flask-RESTful 创建RESTful API:

# 使用 Flask-RESTful 创建RESTful API
# 安装 Flask-RESTful:pip install Flask-RESTful
from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'message': 'Hello, World!'}

api.add_resource(HelloWorld, '/')

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

140. 使用 smtplib 发送电子邮件:

# 使用 smtplib 发送电子邮件
import smtplib
from email.mime.text import MIMEText

# 配置SMTP服务器和端口
smtp_server = 'your_smtp_server'
smtp_port = 587

# 发件人和收件人
sender_email = 'your_email@gmail.com'
receiver_email = 'recipient_email@gmail.com'

# 邮件内容
subject = 'Test Email'
body = 'This is a test email.'

# 创建邮件
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email

# 连接到SMTP服务器并发送邮件
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender_email, 'your_email_password')
    server.sendmail(sender_email, [receiver_email], msg.as_string())
  • 25
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值