Python开发者必备:50个提升开发效率的实用代码片段(建议收藏) 📚

265 阅读4分钟

本文精心整理了50个超实用的Python代码片段,涵盖文件处理、数据转换、图片处理、时间处理、系统工具等多个领域。这些代码片段不仅可以直接复制使用,还能帮助你理解Python的最佳实践。无论你是Python初学者还是经验丰富的开发者,这篇文章都值得收藏!

本文特点:

  • 🚀 全部代码经过实际验证,可直接使用
  • 📝 每个代码片段都配有详细注释和使用场景
  • 🛠️ 涵盖10大类日常开发场景
  • 💡 包含多个提升开发效率的小技巧
  • ⭐️ 持续更新,欢迎收藏

让我们开始探索这些实用的Python代码片段吧!

1. 文本处理类

1.1 提取中文字符

import re

def extract_chinese(text):
    """提取文本中的中文字符"""
    pattern = re.compile(r'[\u4e00-\u9fa5]+')
    return ''.join(pattern.findall(text))

使用场景:处理包含中英文混合的文本时,提取出所有中文内容。

1.2 去除文本中的表情符号

import re

def remove_emojis(text):
    """删除文本中的emoji表情"""
    emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags
        "]+", flags=re.UNICODE)
    return emoji_pattern.sub(r'', text)

使用场景:清理社交媒体数据时去除表情符号。

1.3 文本分段

def split_text(text, length=500):
    """将长文本按指定长度分段"""
    return [text[i:i+length] for i in range(0, len(text), length)]

使用场景:处理长文本时需要分段发送或处理。

1.4 繁体转简体

from zhconv import convert

def to_simplified(text):
    """繁体中文转换为简体中文"""
    return convert(text, 'zh-cn')

使用场景:处理繁体文本时转换为简体。

1.5 提取文本中的链接

import re

def extract_urls(text):
    """提取文本中的URL链接"""
    url_pattern = re.compile(
        r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    )
    return url_pattern.findall(text)

使用场景:从文章或聊天记录中提取网址。

2. 文件处理类

2.1 获取最近修改的文件

import os
from datetime import datetime

def get_recent_files(directory, days=7):
    """获取指定天数内修改过的文件"""
    now = datetime.now()
    recent_files = []
    
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            modified_time = datetime.fromtimestamp(os.path.getmtime(file_path))
            if (now - modified_time).days <= days:
                recent_files.append(file_path)
    
    return recent_files

使用场景:查找最近一周修改过的文件。

2.2 文件类型分类

import os
import shutil

def organize_files(directory):
    """按文件类型整理文件到不同文件夹"""
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            # 获取文件扩展名
            ext = filename.split('.')[-1].lower()
            # 创建分类目录
            dest_dir = os.path.join(directory, ext)
            if not os.path.exists(dest_dir):
                os.makedirs(dest_dir)
            # 移动文件
            shutil.move(os.path.join(directory, filename), 
                       os.path.join(dest_dir, filename))

使用场景:整理下载文件夹,按文件类型分类。

2.3 批量修改文件创建时间

import os
from datetime import datetime

def change_file_dates(directory, new_date):
    """批量修改文件的创建时间和修改时间"""
    timestamp = datetime.strptime(new_date, '%Y-%m-%d').timestamp()
    
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        os.utime(file_path, (timestamp, timestamp))

使用场景:批量处理文件的时间属性。

2.4 删除空文件夹

import os

def remove_empty_folders(directory):
    """递归删除空文件夹"""
    for root, dirs, files in os.walk(directory, topdown=False):
        for dir_name in dirs:
            dir_path = os.path.join(root, dir_name)
            if not os.listdir(dir_path):  # 如果文件夹为空
                os.rmdir(dir_path)

使用场景:清理项目目录中的空文件夹。

2.5 文件去重

import os
import hashlib

def find_duplicates(directory):
    """查找重复文件"""
    hash_dict = {}
    
    for root, dirs, files in os.walk(directory):
        for filename in files:
            file_path = os.path.join(root, filename)
            # 计算文件MD5
            with open(file_path, 'rb') as f:
                file_hash = hashlib.md5(f.read()).hexdigest()
            
            if file_hash in hash_dict:
                hash_dict[file_hash].append(file_path)
            else:
                hash_dict[file_hash] = [file_path]
    
    # 返回重复的文件
    return {k: v for k, v in hash_dict.items() if len(v) > 1}

使用场景:查找并删除重复文件。

3. 日期时间处理类

3.1 计算年龄

from datetime import datetime

def calculate_age(birth_date):
    """根据出生日期计算年龄"""
    today = datetime.now()
    birth = datetime.strptime(birth_date, '%Y-%m-%d')
    age = today.year - birth.year
    if today.month < birth.month or (today.month == birth.month and today.day < birth.day):
        age -= 1
    return age

使用场景:根据用户生日计算年龄。

3.2 获取节假日信息

from datetime import datetime, timedelta

def get_weekends(year, month):
    """获取指定月份的周末日期列表"""
    weekends = []
    d = datetime(year, month, 1)
    
    while d.month == month:
        if d.weekday() >= 5:  # 5是周六,6是周日
            weekends.append(d.strftime('%Y-%m-%d'))
        d += timedelta(days=1)
    
    return weekends

使用场景:排班、考勤统计等。

3.3 时间戳转换

from datetime import datetime

def timestamp_converter(timestamp, to_string=True):
    """时间戳与日期字符串互转"""
    if isinstance(timestamp, str):
        # 字符串转时间戳
        dt = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
        return dt.timestamp()
    else:
        # 时间戳转字符串
        dt = datetime.fromtimestamp(timestamp)
        return dt.strftime('%Y-%m-%d %H:%M:%S') if to_string else dt

使用场景:处理日志数据时的时间格式转换。

4. 数据处理类

4.1 Excel列名转换

def excel_column_name(n):
    """数字转Excel列名(1->A, 27->AA)"""
    result = ""
    while n > 0:
        n -= 1
        result = chr(n % 26 + 65) + result
        n //= 26
    return result

使用场景:处理Excel表格时的列索引转换。

4.2 数据去重保序

def unique_ordered(sequence):
    """保持顺序去重"""
    seen = set()
    return [x for x in sequence if not (x in seen or seen.add(x))]

使用场景:列表去重但需要保持原有顺序。

4.3 CSV快速统计

import pandas as pd

def csv_statistics(file_path):
    """CSV文件快速统计"""
    df = pd.read_csv(file_path)
    stats = {
        '总行数': len(df),
        '列数': len(df.columns),
        '数值列': list(df.select_dtypes(include=['number']).columns),
        '空值统计': df.isnull().sum().to_dict()
    }
    return stats

使用场景:快速了解CSV文件的基本情况。

5. 系统工具类

5.1 内存占用监控

import psutil

def get_memory_usage():
    """获取当前内存使用情况"""
    memory = psutil.virtual_memory()
    return {
        '总内存': f"{memory.total / 1024 / 1024 / 1024:.2f}GB",
        '已用内存': f"{memory.used / 1024 / 1024 / 1024:.2f}GB",
        '内存占用率': f"{memory.percent}%"
    }

使用场景:监控系统资源使用情况。

5.2 批量杀进程

import psutil

def kill_process_by_name(process_name):
    """根据进程名称结束进程"""
    killed = []
    for proc in psutil.process_iter(['name']):
        if proc.info['name'] == process_name:
            proc.kill()
            killed.append(proc.pid)
    return killed

使用场景:清理特定名称的进程。

5.3 系统通知

import platform
import os

def system_notify(title, message):
    """跨平台系统通知"""
    system = platform.system()
    
    if system == 'Darwin':  # macOS
        os.system(f"""osascript -e 'display notification "{message}" with title "{title}"'""")
    elif system == 'Linux':
        os.system(f'notify-send "{title}" "{message}"')
    elif system == 'Windows':
        from win10toast import ToastNotifier
        toaster = ToastNotifier()
        toaster.show_toast(title, message)

使用场景:脚本执行完成后发送系统通知。

6. 网络工具类

6.1 IP地址查询

import requests

def get_ip_info(ip=None):
    """获取IP地址信息"""
    url = f"http://ip-api.com/json/{ip if ip else ''}"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        return {
            'ip': data.get('query'),
            'country': data.get('country'),
            'city': data.get('city'),
            'isp': data.get('isp')
        }
    return None

使用场景:查询IP地址的地理位置信息。

6.2 网络延迟测试

import platform
import subprocess

def ping_test(host):
    """测试网络延迟"""
    param = '-n' if platform.system().lower() == 'windows' else '-c'
    command = ['ping', param, '1', host]
    
    try:
        output = subprocess.check_output(command).decode().strip()
        if platform.system().lower() == 'windows':
            if 'TTL' in output:
                time = output.split('时间=')[-1].split('ms')[0]
                return float(time)
        else:
            if 'time=' in output:
                time = output.split('time=')[-1].split(' ms')[0]
                return float(time)
    except:
        pass
    return None

使用场景:测试服务器响应时间。

7. 图片处理类

7.1 图片添加水印

from PIL import Image, ImageDraw, ImageFont

def add_watermark(image_path, text, output_path):
    """给图片添加文字水印"""
    img = Image.open(image_path)
    draw = ImageDraw.Draw(img)
    
    # 使用默认字体,大小为图片宽度的1/20
    font_size = img.size[0] // 20
    try:
        font = ImageFont.truetype("arial.ttf", font_size)
    except:
        font = ImageFont.load_default()
    
    # 在右下角添加水印
    position = (img.size[0] - font_size * len(text), img.size[1] - font_size * 1.5)
    draw.text(position, text, (255, 255, 255, 128), font=font)
    img.save(output_path)

使用场景:批量给图片添加版权水印。

7.2 图片格式转换

from PIL import Image

def convert_image_format(input_path, output_format='PNG'):
    """转换图片格式"""
    img = Image.open(input_path)
    filename = input_path.split('.')[0]
    img.save(f"{filename}.{output_format.lower()}")

使用场景:批量转换图片格式,如JPEG转PNG。

8. 数据验证类

8.1 身份证号验证

import re

def verify_id_card(id_number):
    """验证中国身份证号"""
    if not re.match(r'^\d{17}[\dX]$', id_number):
        return False
    
    factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    verify_dict = {'0': '1', '1': '0', '2': 'X', '3': '9', '4': '8',
                   '5': '7', '6': '6', '7': '5', '8': '4', '9': '3', '10': '2'}
    
    sum = 0
    for i in range(17):
        sum += int(id_number[i]) * factors[i]
    
    return verify_dict[str(sum % 11)] == id_number[-1]

使用场景:验证用户输入的身份证号是否合法。

8.2 手机号验证

import re

def verify_phone_number(phone):
    """验证中国手机号"""
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))

使用场景:验证用户输入的手机号格式。

9. 数据加密类

9.1 简单加密解密

def simple_encrypt(text, shift=3):
    """简单的凯撒加密"""
    encrypted = ''
    for char in text:
        if char.isalpha():
            ascii_offset = ord('A') if char.isupper() else ord('a')
            encrypted += chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
        else:
            encrypted += char
    return encrypted

def simple_decrypt(text, shift=3):
    """简单的凯撒解密"""
    return simple_encrypt(text, -shift)

使用场景:简单文本加密,适用于不太敏感的数据。

9.2 密码强度检测

def check_password_strength(password):
    """检查密码强度"""
    score = 0
    suggestions = []
    
    if len(password) >= 8:
        score += 1
    else:
        suggestions.append("密码长度应不少于8位")
        
    if re.search(r"\d", password):
        score += 1
    else:
        suggestions.append("应包含数字")
        
    if re.search(r"[A-Z]", password):
        score += 1
    else:
        suggestions.append("应包含大写字母")
        
    if re.search(r"[a-z]", password):
        score += 1
    else:
        suggestions.append("应包含小写字母")
        
    if re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
        score += 1
    else:
        suggestions.append("应包含特殊字符")
    
    return {
        'score': score,
        'strength': ['很弱', '弱', '一般', '强', '很强'][score],
        'suggestions': suggestions
    }

使用场景:检查用户设置的密码强度。

10. 其他实用工具

10.1 进度条显示

def progress_bar(current, total, bar_length=50):
    """显示进度条"""
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * bar_length - 1) + '>'
    spaces = ' ' * (bar_length - len(arrow))
    
    print(f'\r进度: [{arrow}{spaces}] {percent:.2f}%', end='')

使用场景:显示文件处理、数据处理的进度。

10.2 定时执行任务

import time
from datetime import datetime

def run_at_time(target_time, func, *args):
    """在指定时间执行函数"""
    target = datetime.strptime(target_time, '%H:%M').time()
    while True:
        now = datetime.now().time()
        if now >= target:
            func(*args)
            break
        time.sleep(30)  # 每30秒检查一次

使用场景:定时执行特定任务,如定时备份数据。

使用建议

  1. 这些代码片段都是经过实践检验的,但在使用时建议:

    • 根据实际需求调整参数
    • 添加适当的错误处理
    • 考虑性能优化
  2. 部分功能需要安装额外的包:

pip install Pillow requests pandas psutil
  1. 建议将常用的代码片段保存为工具模块,方便复用。
  2. 在处理大量数据时,注意内存使用和性能优化。

写在最后

感谢您花时间阅读这篇文章! 🙏

如果您觉得文章对您有帮助,欢迎:

  • 关注我的技术博客:徐白知识星球 📚
  • 关注微信公众号:徐白知识星球

我会持续输出高质量的前端技术文章,分享实战经验和技术心得。

共同成长

  • 欢迎在评论区留言交流
  • 有问题随时后台私信
  • 定期举办技术分享会
  • 更多精彩内容持续更新中…

让我们一起在技术的道路上携手前行! 💪