python常用代码片段

基本文件读写

with open('file.txt', 'w') as f:
    f.write('Hello, World!')
with open('file.txt', 'r') as f:
    content = f.read()

路径处理

import os
from pathlib import Path
file_path = os.path.join('folder', 'file.txt')
path = Path('folder') / 'file.txt'  # 现代写法

压缩 / 解压缩文件

import zipfile
with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('file.txt')
with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted')

列表推导式

squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]

集合操作

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a.union(b))  # 并集: {1, 2, 3, 4, 5, 6}
print(a.intersection(b))  # 交集: {3, 4}

字符串格式化

name, age = "Alice", 30
print(f"{name}今年{age}岁")  # f-string
print("{0}今年{1}岁".format(name, age))

正则表达式

import re
text = "联系方式: email@example.com 电话123-4567"
emails = re.findall(r'[\w._%+-]+@[\w.-]+\.[a-zA-Z]{2,}', text)
phones = re.findall(r'\d{3}-\d{4}', text)

基本图像操作

from PIL import Image, ImageFilter, ImageDraw
img = Image.open('example.jpg')
print(f"大小: {img.size}, 格式: {img.format}")

图像处理

resized = img.resize((300, 200))
rotated = img.rotate(45)
blurred = img.filter(ImageFilter.BLUR)
cropped = img.crop((100, 100, 400, 400))  # (left, top, right, bottom)

绘图与保存

draw = ImageDraw.Draw(img)
draw.rectangle((50, 50, 150, 150), outline="red")
draw.text((10, 10), "Hello", fill="white")
# 保存图像
img.save('modified.jpg', quality=95)

环境变量操作

import os
from dotenv import load_dotenv
load_dotenv()  # 加载.env文件
api_key = os.getenv('API_KEY', '默认值')
os.environ['DEBUG'] = 'True'  # 设置环境变量

命令行参数

import argparse
parser = argparse.ArgumentParser(description='示例程序')
parser.add_argument('filename', help='输入文件')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()

子进程管理

import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)

单元测试

import unittest
def add(a, b): return a + b
class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)
        self.assertEqual(add(-1, 1), 0)
    def test_add_fail(self):
        self.assertNotEqual(add(1, 1), 3)

性能测量

import time, timeit
def measure():
    start = time.time()
    result = sum(range(1000000))
    print(f"耗时: {time.time() - start}秒")
    return result

迭代工具

from itertools import cycle, chain, islice
colors = cycle(['红', '绿', '蓝'])  # 无限循环
print(next(colors), next(colors))  # 红 绿
combined = chain([1, 2], [3, 4])  # 连接多个可迭代对象
first_5 = islice(fibonacci(100), 5)  # 切片迭代器

创建 DataFrame

import pandas as pd
import numpy as np
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['北京', '上海', '广州']
}
df = pd.DataFrame(data)
df = pd.DataFrame(data)

数据选择与过滤

names = df['Name']  # 选择单列
subset = df[['Name', 'Age']]  # 选择多列
young = df[df['Age'] < 30]  # 条件过滤

数据分析

print(df.describe())  # 统计摘要
grouped = df.groupby('City').mean()  # 分组统计

函数缓存提高性能

from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
    if n <= 1: return n
    return fibonacci(n-1) + fibonacci(n-2)

命名元组

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)  # 通过名称访问元素

枚举类型

from enum import Enum, auto
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = auto()  # 自动赋值

数据类

from dataclasses import dataclass
@dataclass
class Product:
    name: str
    price: float
    quantity: int = 0
def total_cost(self) -> float:
    return self.price * self.quantity

Base64 编码

import base64
encoded = base64.b64encode("Hello".encode())
decoded = base64.b64decode(encoded).decode()

装饰器

import time
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"耗时: {time.time() - start}秒")
        return result
    return wrapper

Lambda 表达式

add = lambda x, y: x + y
sorted_items = sorted(items, key=lambda x: x[1])

参数解包

def add(a, b, c): return a + b + c
values = [1, 2, 3]
print(add(*values))  # 解包列表
params = {'a': 1, 'b': 2, 'c': 3}
print(add(**params))  # 解包字典

CSV 处理

import csv
with open('data.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows([['Name', 'Age'], ['Alice', 25]])
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

XML 处理

import xml.etree.ElementTree as ET
xml_str = '<root><item id="1">值</item></root>'
root = ET.fromstring(xml_str)
value = root.find('item').text

HTTP 请求

import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
    data = response.json()

解析网页

from bs4 import BeautifulSoup
html = requests.get('https://example.com').text
soup = BeautifulSoup(html, 'html.parser')
title = soup.title.text
links = soup.find_all('a')

属性装饰器

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def celsius(self):
        return self._celsius
    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

魔术方法

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

生成器函数

def fibonacci(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a + b

生成器表达式

squares = (x**2 for x in range(10))  # 比列表推导省内存

获取和格式化当前时间

from datetime import datetime, timedelta
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"当前时间: {formatted}")

日期计算

tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
time_diff = tomorrow - now  # 计算时间差

解析日期字符串

date_str = "2023-01-15"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")

JSON 处理

import json
data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(data, indent=2)  # 转为JSON
parsed = json.loads(json_str)  # 解析JSON

URL 解析与构建

from urllib.parse import urlparse, urlencode
parsed_url = urlparse("https://example.com/path")
params = {"name": "张三", "age": 30}
query = urlencode(params)

异常处理

try:
    result = 10 / 0  # 会引发ZeroDivisionError
except ZeroDivisionError as e:
    print(f"捕获到错误: {e}")
except Exception as e:
    print(f"捕获其他错误: {e}")
finally:
    print("始终执行的代码")

日志记录

import logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='app.log'
)
logging.info('程序启动')
logging.warning('警告信息')
logging.error('错误信息')

多线程

import threading
def task(name):
    print(f"线程{name}运行中")
threads = [threading.Thread(target=task, args=(i,)) for i in range(3)]
for t in threads:
    t.start()

异步编程

import asyncio
async def say_hello(delay, name):
    await asyncio.sleep(delay)
    print(f"Hello, {name}")
async def main():
    await asyncio.gather(
        say_hello(1, "Alice"),
        say_hello(2, "Bob")
    )
# asyncio.run(main())  # Python 3.7+

连接和创建表

import sqlite3
# 连接数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)''')

数据库操作

# 插入数据
cursor.execute("INSERT INTO users VALUES (?, ?, ?)", (1, 'Alice', 25))
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM users WHERE age > ?", (20,))
for row in cursor.fetchall():
    print(row)
conn.close()

基本类定义

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def greet(self):
        return f"你好,我是{self.name}"
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇