Python语法及常用用法(5)
111. 使用 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
生成数据分析报告:
import pandas as pd
from pandas_profiling import ProfileReport
data = pd.read_csv("example.csv")
profile = ProfileReport(data)
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:
import hug
@hug.get("/")
def hello():
return {"message": "Hello, Hug!"}
115. 使用 openpyxl
处理 Excel 文件:
import openpyxl
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet["A1"] = "Hello"
sheet["B1"] = "World"
workbook.save("example.xlsx")
116. 使用 python-docx
处理 Word 文档:
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 脚本打包成可执行文件:
118. 使用 youtube_dl
下载 YouTube 视频:
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
模块进行高级正则表达式操作:
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
处理时区:
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 自动化测试:
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
进行迭代操作:
import itertools
count = itertools.count(start=1, step=2)
for _ in range(5):
print(next(count))
123. 使用 Faker
生成虚拟数据:
from faker import Faker
fake = Faker()
name = fake.name()
address = fake.address()
print("Name:", name)
print("Address:", address)
124. 使用 tqdm
创建进度条:
from tqdm import tqdm
import time
for _ in tqdm(range(10), desc="Processing"):
time.sleep(0.1)
125. 使用 PyQt
创建桌面应用程序:
from PyQt5.QtWidgets import QApplication, QLabel
app = QApplication([])
window = QLabel("Hello, PyQt!")
window.show()
app.exec_()
126. 使用 fastapi
和 uvicorn
创建异步 Web API:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello, FastAPI!"}
127. 使用 beautifulsoup4
进行网页解析:
from bs4 import BeautifulSoup
import requests
url = 'https://www.example.com'
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
title = soup.title.string
print("Title:", title)
128. 使用 paramiko
进行SSH操作:
import paramiko
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.close()
129. 使用 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
创建交互式图表:
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
分析图结构:
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文件:
import h5py
with h5py.File('example.h5', 'w') as file:
dataset = file.create_dataset('my_dataset', data=[1, 2, 3])
print(dataset[:])
133. 使用 PyQt
创建自定义对话框:
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
模块检测图像文件类型:
import imghdr
image_path = 'example.jpg'
image_type = imghdr.what(image_path)
print("Image Type:", image_type)
135. 使用 jsonpickle
序列化/反序列化复杂对象:
import jsonpickle
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
json_str = jsonpickle.encode(person)
print(json_str)
decoded_person = jsonpickle.decode(json_str)
print(decoded_person.name, decoded_person.age)
136. 使用 sqlite3
模块进行SQLite数据库操作:
import sqlite3
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
进行鼠标和键盘自动化:
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存储:
import boto3
aws_access_key = 'your_access_key'
aws_secret_key = 'your_secret_key'
region = 'your_region'
s3 = boto3.client('s3', aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, region_name=region)
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:
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
发送电子邮件:
import smtplib
from email.mime.text import MIMEText
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
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())