Repository navigation
Expand file tree
/
Copy path3_2_stdlib_libs.py
More file actions
180 lines (142 loc) · 6.14 KB
/
Copy path3_2_stdlib_libs.py
File metadata and controls
180 lines (142 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
================================================================
第三阶段:标准库与工程化必备
3.2 常用标准库进阶(datetime、random、re、math)
================================================================
【课程属性】L1/L2 · 必修 · 预计 60~120 分钟
【前置要求】完成 3.1 文件、路径、JSON 与 CSV
【学习目标】
1. 掌握日期时间处理(datetime)
2. 掌握随机数生成(random)
3. 掌握正则表达式(re)的常用匹配方式
4. 了解数学计算(math, decimal, fractions)
【本课 Python 知识点】
- datetime/strftime/strptime - random 常用方法
- re 模块 match/search/findall/sub
- math/decimal/fractions
【参考链接】
re 官方文档: https://docs.python.org/zh-cn/3/library/re.html
正则表达式教程: https://regex101.com/(在线测试)
datetime: https://docs.python.org/zh-cn/3/library/datetime.html
"""
# ============================================================
# 第一部分:日期时间 datetime
# ============================================================
from datetime import datetime, date, timedelta
# 获取当前时间
now = datetime.now()
# print(now) # 2025-06-15 14:30:00.123456
# 创建指定时间
dt = datetime(2025, 6, 15, 14, 30, 0)
# 格式化输出:strftime(datetime → 字符串)
print(dt.strftime("%Y-%m-%d")) # 2025-06-15
print(dt.strftime("%Y年%m月%d日 %H:%M")) # 2025年06月15日 14:30
print(dt.strftime("%A")) # Sunday(星期几,英文)
# 解析字符串:strptime(字符串 → datetime)
# date_str = "2025-06-15 14:30:00"
# parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
# 常用格式化符号:
# %Y 四位年 %m 月 %d 日 %H 时 %M 分 %S 秒
# %A 星期全称 %a 星期简称 %B 月份全称
# 日期运算:timedelta
tomorrow = now + timedelta(days=1)
one_week_ago = now - timedelta(weeks=1)
delta = tomorrow - now
print(delta.days) # 1
# 只取日期或时间:
print(now.date()) # 2025-06-15
print(now.time()) # 14:30:00
# ============================================================
# 第二部分:随机数 random
# ============================================================
import random
random.random() # 0.0 ~ 1.0 之间的浮点
random.randint(1, 100) # 1 ~ 100 之间的整数(含两端)
random.choice(["石头", "剪刀", "布"]) # 从序列中随机选一个
random.uniform(0, 1) # 0~1 均匀分布浮点
# 从列表中随机取多个:
cards = ["A", "2", "3", "4", "5"]
hand = random.sample(cards, k=3) # 不重复抽取3个
random.shuffle(cards) # 原地打乱列表
# 设置种子:让随机可复现(测试用)
random.seed(42)
print(random.randint(1, 100)) # 每次运行都一样
random.seed(42)
print(random.randint(1, 100)) # 相同的值
# ============================================================
# 第三部分:正则表达式 re —— 文本处理重点
# ============================================================
import re
# 常用函数:
# re.match(pattern, s):从开头匹配
# re.search(pattern, s):搜索第一个匹配
# re.findall(pattern, s):找全部匹配,返回列表
# re.sub(pattern, repl, s):替换
# 基本元字符:
# . 任意字符(除换行)
# * 前一个字符 0 次或多次
# + 前一个字符 1 次或多次
# ? 前一个字符 0 次或 1 次
# ^ 开头 $ 结尾
# [] 字符集 [0-9] [a-z]
# \d 数字 \w 字母数字下划线 \s 空白
# {n} 恰好 n 次 {n,m} n 到 m 次
# 1. 匹配电话号码:1[3-9]\d{9}
phone = "我的电话是13812345678"
match = re.search(r"1[3-9]\d{9}", phone)
if match:
print(match.group()) # 13812345678
# 2. findall 提取邮箱
text = "联系 a@test.com 或 b@example.org"
emails = re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)
# ['a@test.com', 'b@example.org']
# 3. 分组提取(用括号)
date_text = "今天2025-06-15发布"
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", date_text)
if m:
year, month, day = m.groups() # ('2025', '06', '15')
# 4. 替换
censored = re.sub(r"\d{11}", "******", phone)
# "我的电话是******"
# 5. 常用验证(手机号、邮箱、身份证)
def is_valid_phone(phone_number: str) -> bool:
"""验证 11 位手机号"""
return bool(re.fullmatch(r"1[3-9]\d{9}", phone_number))
print(is_valid_phone("13812345678")) # True
print(is_valid_phone("12345")) # False
# 原始字符串 r"...":正则表达式里的反斜杠不需要转义
# 不加 r 要写 \\d,加了 r 直接写 \d(推荐)
# ============================================================
# 第四部分:数学计算
# ============================================================
import math
math.sqrt(16) # 4.0
math.floor(3.7) # 3(向下取整)
math.ceil(3.2) # 4(向上取整)
math.pow(2, 10) # 1024.0
math.pi # 3.14159...
math.inf # 正无穷
# decimal:解决浮点精度问题(1.2 课的 0.1+0.2)
from decimal import Decimal
print(0.1 + 0.2) # 0.30000000000000004
print(Decimal("0.1") + Decimal("0.2")) # 0.3(精确!)
# 注意:Decimal 要用字符串构造,Decimal(0.1) 反而会保留二进制误差
# 思考:什么时候用 Decimal?
# 金融计算(钱!)、需要精确小数的场景
# 普通科学计算用 float 就行(快)
# fractions:分数运算
from fractions import Fraction
print(Fraction(1, 3) + Fraction(1, 6)) # 1/2
# ============================================================
# 本课小结
# ============================================================
#
# [ ] 会 strftime/strptime 互转
# [ ] 知道 random.seed 的用途
# [ ] 能写出手机号和邮箱的正则
# [ ] 知道 Decimal 解决什么问题
# ============================================================
# 课后练习(见 exercises/3_2_stdlib.py)
# ============================================================