Python--内置模块和开发规范(上)

1. 内置模块

1.1 JSON 模块

核心功能
  • 序列化:Python 数据类型 → JSON 字符串

    import json
    data = [{"id": 1, "name": "武沛齐"}, {"id": 2, "name": "Alex"}]
    json_str = json.dumps(data, ensure_ascii=False)  # 禁用 ASCII 转义
    
  • 反序列化:JSON 字符串 → Python 数据类型

    data_list = json.loads('[{"id": 1, "name": "武沛齐"}]')
    
特殊类型支持
  • 自定义编码器:处理 Decimal​、datetime​ 等非默认类型

    class MyJSONEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, Decimal): return str(o)
            elif isinstance(o, datetime): return o.isoformat()
            return super().default(o)
    
    json_str = json.dumps(data, cls=MyJSONEncoder)
    
文件操作
  • 写入文件

    with open("data.json", "w") as f:
        json.dump(data, f)
    
  • 读取文件

    with open("data.json", "r") as f:
        data = json.load(f)
    

1.2 时间处理模块

time​ 模块
  • 基础功能

    import time
    timestamp = time.time()        # 当前时间戳(秒)
    time.sleep(3)                  # 暂停 3 秒
    
datetime​ 模块
  • 时间对象操作

    from datetime import datetime, timedelta
    
    now = datetime.now()                          # 本地时间
    utc_time = datetime.utcnow()                  # UTC 时间
    future = now + timedelta(days=7, hours=3)     # 时间加减
    
  • 格式化与解析

    text = "2023-10-01 12:30"
    dt = datetime.strptime(text, "%Y-%m-%d %H:%M")  # 字符串 → datetime
    formatted = dt.strftime("%Y/%m/%d")             # datetime → 字符串
    
  • 时间戳转换

    timestamp = dt.timestamp()                    # datetime → 时间戳
    dt_from_ts = datetime.fromtimestamp(1672500000)  # 时间戳 → datetime
    

1.3 正则表达式(re 模块)

语法要点
  • 基础匹配

    import re
    re.findall(r"\d+", "ID: 123, Name: Alex")     # 匹配数字 → ['123']
    
  • 分组与命名分组

    match = re.search(r"(?P\d{4})-(?P\d{2})", "2023-10")
    if match:
        print(match.groupdict())  # {'year': '2023', 'month': '10'}
    
  • 贪婪与非贪婪匹配

    re.findall(r"a.+b", "aabb")       # 贪婪 → ['aabb']
    re.findall(r"a.+?b", "aabb")      # 非贪婪 → ['aab']
    
常用方法
  • 替换与分割

    re.sub(r"\d+", "X", "ID: 123")    # 替换 → "ID: X"
    re.split(r",\s*", "a, b, c")      # 分割 → ['a', 'b', 'c']
    

你可能感兴趣的:(Python安全开发,python,开发语言,windows,网络安全,web安全,笔记)