Learning Python3 in 常用标准library, Master各种 in 置module usingmethod
Python标准library is Pythonlanguage in 置 一系列module and package, 它们providing了丰富 functions, 涵盖了 from fileoperation, network通信 to dataprocessing, graph形界面etc.各个方面. 标准library 优点including:
本tutorial将介绍Python标准libraryin最常用 一些module, helping你 fast 速Master它们 usingmethod.
osmoduleproviding了 and operationsystem交互 functions, includingfile and Table of Contentsoperation, environmentvariablemanagement, processmanagementetc..
import os
# 获取当 before 工作Table of Contents
print(f"当 before 工作Table of Contents: {os.getcwd()}")
# 改变当 before 工作Table of Contents
# os.chdir("/path/to/directory")
# 列出Table of Contents in 容
print("\nTable of Contents in 容:")
for item in os.listdir("."):
print(f"- {item}")
# creationTable of Contents
if not os.path.exists("test_dir"):
os.mkdir("test_dir")
print("\ncreationTable of Contents 'test_dir' 成功")
# checkpath
print("\npathcheck:")
print(f"'test_dir' is 否存 in : {os.path.exists('test_dir')}")
print(f"'test_dir' is 否 for Table of Contents: {os.path.isdir('test_dir')}")
print(f"'example.txt' is 否 for file: {os.path.isfile('example.txt')}")
# 获取environmentvariable
print("\nenvironmentvariable:")
print(f"HOME: {os.environ.get('HOME', 'Not found')}")
print(f"PATH: {os.environ.get('PATH', 'Not found')[:100]}...")
# 执行systemcommands
print("\n执行systemcommands:")
os.system("echo Hello from os.system")
# usingsubprocessmodule执行commands (推荐)
import subprocess
print("\nusingsubprocess执行commands:")
result = subprocess.run(["echo", "Hello from subprocess"], capture_output=True, text=True)
print(f"commands输出: {result.stdout.strip()}")
sysmoduleproviding了 and Python解释器相关 functions, includingcommands行parameter, module搜索path, 标准输入输出etc..
import sys
# commands行parameter
print(f"commands行parameter: {sys.argv}")
# Pythonversion
print(f"Pythonversion: {sys.version}")
# module搜索path
print("\nmodule搜索path:")
for path in sys.path:
print(f"- {path}")
# 标准输入输出
print("\n标准输出example")
sys.stdout.write("这 is throughsys.stdout写入 输出\n")
# 退出程序
# sys.exit(0) # 0表示正常退出, 非0表示error退出
# 获取平台information
print(f"\n平台information: {sys.platform}")
# 获取最 big 整数
print(f"最 big 整数: {sys.maxsize}")
datetimemoduleproviding了processing日期 and 时间 functions, including日期计算, formatetc..
from datetime import datetime, date, time, timedelta
# 获取当 before 日期 and 时间
now = datetime.now()
print(f"当 before 日期 and 时间: {now}")
print(f"年: {now.year}")
print(f"月: {now.month}")
print(f"日: {now.day}")
print(f"时: {now.hour}")
print(f"分: {now.minute}")
print(f"秒: {now.second}")
print(f"微秒: {now.microsecond}")
# creation日期object
d = date(2023, 12, 25)
print(f"\ncreation 日期: {d}")
# creation时间object
t = time(10, 30, 45)
print(f"creation 时间: {t}")
# creation日期时间object
dt = datetime(2023, 12, 25, 10, 30, 45)
print(f"creation 日期时间: {dt}")
# 日期时间format
print("\n日期时间format:")
print(f"YYYY-MM-DD HH:MM:SS: {dt.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"MM/DD/YYYY: {dt.strftime('%m/%d/%Y')}")
print(f"HH:MM AM/PM: {dt.strftime('%I:%M %p')}")
# 解析string for 日期时间
print("\n解析string for 日期时间:")
date_str = "2023-12-25"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(f"解析结果: {date_obj}")
# 日期时间计算
print("\n日期时间计算:")
today = date.today()
print(f"今天: {today}")
yesterday = today - timedelta(days=1)
print(f"昨天: {yesterday}")
tomorrow = today + timedelta(days=1)
print(f"明天: {tomorrow}")
# 计算两个日期之间 差值
birthday = date(1990, 1, 1)
age = today - birthday
print(f"\n from 1990-01-01 to 今天 天数: {age.days}")
print(f" from 1990-01-01 to 今天 年数: {age.days // 365}")
timemoduleproviding了 and 时间相关 functions, including时间获取, latency执行etc..
import time
# 获取当 before 时间戳 ( from 1970年1月1日开始 秒数)
timestamp = time.time()
print(f"当 before 时间戳: {timestamp}")
# 将时间戳转换 for 本地时间
local_time = time.localtime(timestamp)
print(f"本地时间: {local_time}")
# format时间
print(f"format时间: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)}")
# latency执行
print("\n开始latency...")
time.sleep(2) # latency2秒
print("latency结束")
# 测量code执行时间
start_time = time.time()
# 执行一些operation
for i in range(1000000):
pass
end_time = time.time()
execution_time = end_time - start_time
print(f"\ncode执行时间: {execution_time:.6f} 秒")
mathmoduleproviding了数学function, including三角function, for 数function, 指数functionetc..
import math
# 常量
print(f"π: {math.pi}")
print(f"e: {math.e}")
# basic运算
print(f"\n绝 for 值: {math.fabs(-10.5)}")
print(f"向 on 取整: {math.ceil(3.2)}")
print(f"向 under 取整: {math.floor(3.8)}")
print(f"四舍五入: {round(3.5)}")
print(f"幂运算: {math.pow(2, 3)}")
print(f"平方根: {math.sqrt(16)}")
# 三角function
print("\n三角function:")
print(f"sin(π/2): {math.sin(math.pi/2)}")
print(f"cos(π): {math.cos(math.pi)}")
print(f"tan(π/4): {math.tan(math.pi/4)}")
print(f"弧度转角度: {math.degrees(math.pi/2)}")
print(f"角度转弧度: {math.radians(90)}")
# for 数function
print("\n for 数function:")
print(f"自然 for 数: {math.log(math.e)}")
print(f"以10 for 底 for 数: {math.log10(100)}")
print(f"以2 for 底 for 数: {math.log2(8)}")
# otherfunction
print("\notherfunction:")
print(f"阶乘: {math.factorial(5)}")
print(f"最 big 公约数: {math.gcd(12, 18)}")
print(f"最 small 公倍数: {math.lcm(12, 18)}")
print(f"双曲正弦: {math.sinh(0)}")
print(f"双曲余弦: {math.cosh(0)}")
randommoduleproviding了生成随机数 functions, including随机整数, 随机浮点数, 随机选择etc..
import random
# 生成随机浮点数 (0.0 to 1.0之间)
print(f"随机浮点数: {random.random()}")
# 生成指定范围 in 随机整数
print(f"\n1 to 10之间 随机整数: {random.randint(1, 10)}")
print(f"0 to 9之间 随机整数: {random.randrange(10)}")
print(f"1 to 10之间步 long for 2 随机整数: {random.randrange(1, 10, 2)}")
# 生成指定范围 in 随机浮点数
print(f"\n1 to 10之间 随机浮点数: {random.uniform(1, 10)}")
# 随机选择
print(f"\n随机选择:")
fruits = ["苹果", "香蕉", "橙子", "葡萄", "草莓"]
print(f" from listin随机选择一个元素: {random.choice(fruits)}")
print(f" from listin随机选择3个元素: {random.sample(fruits, 3)}")
# 打乱序列
print(f"\n打乱序列:")
random.shuffle(fruits)
print(f"打乱 after list: {fruits}")
# 随机种子
print(f"\n随机种子:")
random.seed(42) # 设置种子
print(f"设置种子 after 随机数: {random.random()}")
random.seed(42) # 再次设置相同 种子
print(f"再次设置相同种子 after 随机数: {random.random()}") # 结果相同
collectionsmoduleproviding了额 out containersdataclass型, scale了Python in 置 list, dictionary, 元组etc.class型.
from collections import Counter, defaultdict, OrderedDict, namedtuple, deque
# Counter - 计数器
print("Counter:")
text = "hello world hello python"
word_counts = Counter(text.split())
print(f"单词计数: {word_counts}")
print(f"出现次数最 many 2个单词: {word_counts.most_common(2)}")
# defaultdict - 默认dictionary
print("\ndefaultdict:")
d = defaultdict(int) # 默认值 for 0
for word in text.split():
d[word] += 1
print(f"单词计数: {dict(d)}")
# usinglistserving as默认值
d = defaultdict(list)
d["fruits"].append("苹果")
d["fruits"].append("香蕉")
d["vegetables"].append("西红柿")
print(f"默认dictionary (list) : {dict(d)}")
# OrderedDict - has 序dictionary ( in Python 3.7+in, 普通dictionary也保持插入顺序)
print("\nOrderedDict:")
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3
print(f" has 序dictionary: {dict(od)}")
# namedtuple - 命名元组
print("\nnamedtuple:")
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(f"命名元组: {p}")
print(f"x坐标: {p.x}")
print(f"y坐标: {p.y}")
# deque - 双端queue
print("\ndeque:")
dq = deque([1, 2, 3, 4, 5])
print(f"初始queue: {list(dq)}")
# from right 侧添加元素
dq.append(6)
print(f" right 侧添加 after : {list(dq)}")
# from left 侧添加元素
dq.appendleft(0)
print(f" left 侧添加 after : {list(dq)}")
# from right 侧移除元素
dq.pop()
print(f" right 侧移除 after : {list(dq)}")
# from left 侧移除元素
dq.popleft()
print(f" left 侧移除 after : {list(dq)}")
# 旋转
dq.rotate(1) # 向 right 旋转1位
print(f"向 right 旋转1位 after : {list(dq)}")
dq.rotate(-1) # 向 left 旋转1位
print(f"向 left 旋转1位 after : {list(dq)}")
remoduleproviding了正则表达式 functions, 用于string 匹配, 搜索, replaceetc.operation.
import re
# 匹配string
pattern = r"\d+" # 匹配一个 or many 个number
text = "There are 123 apples and 456 oranges."
# search - find第一个匹配
match = re.search(pattern, text)
if match:
print(f"找 to 匹配: {match.group()}")
print(f"匹配开始位置: {match.start()}")
print(f"匹配结束位置: {match.end()}")
# findall - find所 has 匹配
matches = re.findall(pattern, text)
print(f"\n所 has 匹配: {matches}")
# finditer - find所 has 匹配并返回iterators
print("\nusingfinditer:")
for match in re.finditer(pattern, text):
print(f"匹配: {match.group()}, 位置: {match.span()}")
# split - 根据匹配分割string
print(f"\n根据number分割: {re.split(pattern, text)}")
# sub - replace匹配
print(f"\nreplacenumber for 'NUM': {re.sub(pattern, 'NUM', text)}")
# 更 complex 正则表达式
print("\n更 complex 正则表达式:")
# 匹配邮箱地址
email_pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = "Contact Us: admin@example.com, support@test.org"
email_matches = re.findall(email_pattern, emails)
print(f"找 to 邮箱地址: {email_matches}")
# 匹配URL
url_pattern = r"https?://[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?"
urls = "访问我们 网站: https://www.example.com and http://test.org/path"
url_matches = re.findall(url_pattern, urls)
print(f"找 to URL: {[match[0] for match in url_matches]}")
jsonmoduleproviding了JSONdata 编码 and 解码functions, 用于 in Pythonobject and JSONstring之间for转换.
import json
# Pythonobject转JSONstring
print("Pythonobject转JSONstring:")
data = {
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "traveling", "coding"],
"is_student": False
}
json_str = json.dumps(data, indent=2, ensure_ascii=False)
print(f"JSONstring: {json_str}")
# JSONstring转Pythonobject
print("\nJSONstring转Pythonobject:")
json_str = '''
{
"name": "Bob",
"age": 25,
"city": "London",
"hobbies": ["football", "music", "gaming"],
"is_student": True
}
'''
python_obj = json.loads(json_str)
print(f"Pythonobject: {python_obj}")
print(f"姓名: {python_obj['name']}")
print(f"年龄: {python_obj['age']}")
print(f"爱 good : {python_obj['hobbies']}")
# 读写JSONfile
print("\n读写JSONfile:")
# 写入JSONfile
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print("写入JSONfile成功")
# 读取JSONfile
with open("data.json", "r", encoding="utf-8") as f:
loaded_data = json.load(f)
print(f" from file读取 data: {loaded_data}")
csvmoduleproviding了CSV (逗号分隔值) file 读写functions.
import csv
# 写入CSVfile
print("写入CSVfile:")
data = [
["姓名", "年龄", "城市"],
["Alice", 30, "New York"],
["Bob", 25, "London"],
["Charlie", 35, "Paris"]
]
with open("data.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)
print("写入CSVfile成功")
# 读取CSVfile
print("\n读取CSVfile:")
with open("data.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# usingDictWriter and DictReader
print("\nusingDictWriter and DictReader:")
fieldnames = ["姓名", "年龄", "城市"]
dict_data = [
{"姓名": "David", "年龄": 40, "城市": "Tokyo"},
{"姓名": "Eve", "年龄": 28, "城市": "Sydney"}
]
# 写入
with open("dict_data.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(dict_data)
print("写入Dict CSVfile成功")
# 读取
print("\n读取Dict CSVfile:")
with open("dict_data.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
print(f"姓名: {row['姓名']}, 年龄: {row['年龄']}, 城市: {row['城市']}")
creation一个 simple filemanagement器, usingos, shutiletc.moduleimplementationfile and Table of Contents managementfunctions.
import os
import shutil
import datetime
def list_files(directory="."):
"""
列出Table of Contentsin file and 子Table of Contents
"""
print(f"Table of Contents in 容: {directory}")
print("-" * 50)
print(f"{'名称':<30} {'class型':<10} {' big small ':<10} {'modify时间':<20}")
print("-" * 50)
for item in sorted(os.listdir(directory)):
item_path = os.path.join(directory, item)
if os.path.isdir(item_path):
item_type = "Table of Contents"
size = "-"
else:
item_type = "file"
size = f"{os.path.getsize(item_path)} 字节"
mod_time = os.path.getmtime(item_path)
mod_time_str = datetime.datetime.fromtimestamp(mod_time).strftime("%Y-%m-%d %H:%M:%S")
print(f"{item:<30} {item_type:<10} {size:<10} {mod_time_str:<20}")
print("-" * 50)
def create_directory(directory):
"""
creationTable of Contents
"""
try:
os.makedirs(directory, exist_ok=True)
print(f"creationTable of Contents成功: {directory}")
except Exception as e:
print(f"creationTable of Contents失败: {e}")
def copy_file(src, dst):
"""
copyfile
"""
try:
shutil.copy2(src, dst)
print(f"copyfile成功: {src} -> {dst}")
except Exception as e:
print(f"copyfile失败: {e}")
def move_file(src, dst):
"""
movefile
"""
try:
shutil.move(src, dst)
print(f"movefile成功: {src} -> {dst}")
except Exception as e:
print(f"movefile失败: {e}")
def delete_file(path):
"""
deletefile or Table of Contents
"""
try:
if os.path.isfile(path):
os.remove(path)
print(f"deletefile成功: {path}")
elif os.path.isdir(path):
shutil.rmtree(path)
print(f"deleteTable of Contents成功: {path}")
else:
print(f"path不存 in : {path}")
except Exception as e:
print(f"delete失败: {e}")
def main():
"""
主function
"""
while True:
print("\nfilemanagement器")
print("1. 列出Table of Contents in 容")
print("2. creationTable of Contents")
print("3. copyfile")
print("4. movefile")
print("5. deletefile/Table of Contents")
print("0. 退出")
choice = input("请选择operation: ")
if choice == "1":
directory = input("请输入Table of Contentspath (默认 for 当 before Table of Contents) : ") or "."
list_files(directory)
elif choice == "2":
directory = input("请输入要creation Table of Contentspath: ")
create_directory(directory)
elif choice == "3":
src = input("请输入sourcesfilepath: ")
dst = input("请输入目标filepath: ")
copy_file(src, dst)
elif choice == "4":
src = input("请输入sourcesfilepath: ")
dst = input("请输入目标filepath: ")
move_file(src, dst)
elif choice == "5":
path = input("请输入要delete file or Table of Contentspath: ")
delete_file(path)
elif choice == "0":
print("退出filemanagement器")
break
else:
print("无效 选择, 请重 new 输入")
if __name__ == "__main__":
main()
creation一个日期计算器, usingdatetimemodule计算两个日期之间 天数, or 者计算给定日期之 after or 之 before 日期.
from datetime import datetime, timedelta
def date_calculator():
"""
日期计算器
"""
print("日期计算器")
print("1. 计算两个日期之间 天数")
print("2. 计算给定日期之 after 日期")
print("3. 计算给定日期之 before 日期")
choice = input("请选择operation: ")
if choice == "1":
# implementation你 code
pass
elif choice == "2":
# implementation你 code
pass
elif choice == "3":
# implementation你 code
pass
else:
print("无效 选择")
if __name__ == "__main__":
date_calculator()
creation一个password生成器, usingrandommodule生成指定 long 度 and complexity 随机password.
import random
import string
def generate_password(length=12, include_uppercase=True, include_lowercase=True, include_digits=True, include_symbols=True):
"""
生成随机password
Args:
length: password long 度
include_uppercase: is 否package含 big 写字母
include_lowercase: is 否package含 small 写字母
include_digits: is 否package含number
include_symbols: is 否package含特殊字符
Returns:
str: 生成 password
"""
# implementation你 code
pass
def main():
"""
主function
"""
print("password生成器")
length = int(input("请输入password long 度 (默认 for 12) : ") or "12")
print("\npasswordcomplexity选项:")
include_uppercase = input("package含 big 写字母?(y/n, 默认y): ").lower() != "n"
include_lowercase = input("package含 small 写字母?(y/n, 默认y): ").lower() != "n"
include_digits = input("package含number?(y/n, 默认y): ").lower() != "n"
include_symbols = input("package含特殊字符?(y/n, 默认y): ").lower() != "n"
password = generate_password(
length=length,
include_uppercase=include_uppercase,
include_lowercase=include_lowercase,
include_digits=include_digits,
include_symbols=include_symbols
)
print(f"\n生成 password: {password}")
if __name__ == "__main__":
main()
creation一个文本analysistool, usingcollectionsmoduleanalysis文本in 单词频率, 最 long 单词etc..
from collections import Counter
import re
def analyze_text(text):
"""
analysis文本
Args:
text: 要analysis 文本
Returns:
dict: analysis结果
"""
# implementation你 code
pass
def main():
"""
主function
"""
print("文本analysistool")
text = input("请输入要analysis 文本: ")
result = analyze_text(text)
print("\nanalysis结果:")
print(f"总字符数: {result['total_characters']}")
print(f"总单词数: {result['total_words']}")
print(f"唯一单词数: {result['unique_words']}")
print(f"最 long 单词: {result['longest_word']}")
print(f"出现频率最 high 5个单词: {result['most_common_words']}")
if __name__ == "__main__":
main()