第1课python_常用标准库
热度🔥:100 免费课程
授课语音
Python常用标准库
1. 介绍
Python内置了一些常用标准库,以下是一些主要的库:
- datetime:提供处理日期和时间的方法。
- math:为浮点运算提供对底层C函数库的访问,包含许多数学函数,如圆周率、自然数e及常用数学运算。
- os:提供与操作系统相关的函数,支持文件和目录操作、环境变量获取、执行系统指令等。
- sys:处理Python解释器和系统相关的信息,获取Python版本、操作系统平台、命令行参数等。
- json:轻量级的数据交换格式,支持数据的存储和交换。可用于序列化和反序列化对象。
- re:正则表达式工具,用于搜索、匹配和替换文本。
- collections:包含一些常用数据结构,如双向队列deque、计数器Counter等,方便数据处理。
- itertools:用于迭代和组合的工具函数,处理迭代器、排列组合、循环等。
- functools:包含一些高阶函数,如reduce、wraps等,便于处理函数和参数。
2. 代码案例
# 1. datetime 库
import datetime
# 获取当前日期和时间
now = datetime.datetime.now()
print(f"当前时间: {now}") # 输出当前日期和时间
# 获取今天的日期
today = datetime.date.today()
print(f"今天的日期: {today}") # 输出今天的日期
# 计算未来日期
future_date = today + datetime.timedelta(days=5)
print(f"5天后的日期: {future_date}") # 输出5天后的日期
# 2. math 库
import math
# 获取圆周率
print(f"圆周率: {math.pi}") # 输出圆周率
# 计算平方根
print(f"平方根 (16): {math.sqrt(16)}") # 输出16的平方根
# 计算幂
print(f"幂 (2^3): {math.pow(2, 3)}") # 输出2的3次方
# 计算正弦值
print(f"正弦 (90度): {math.sin(math.radians(90))}") # 输出90度的正弦值
# 3. os 库
import os
# 获取当前工作目录
print(f"当前工作目录: {os.getcwd()}") # 输出当前工作目录
# 创建新目录
os.makedirs('example_dir', exist_ok=True) # 创建新目录,如果已存在则不报错
print(f"目录是否存在: {os.path.exists('example_dir')}") # 检查目录是否存在
# 删除目录
os.rmdir('example_dir') # 删除创建的目录
# 4. sys 库
import sys
# 获取 Python 版本
print(f"Python 版本: {sys.version}") # 输出Python版本信息
# 获取模块搜索路径
print(f"模块搜索路径: {sys.path}") # 输出模块搜索路径
# 获取命令行参数
print(f"命令行参数: {sys.argv}") # 输出脚本的命令行参数
# 5. json 库
import json
# 将 Python 对象转换为 JSON 字符串
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
json_str = json.dumps(data)
print(f"JSON 字符串: {json_str}") # 输出转换后的 JSON 字符串
# 将 JSON 字符串转换为 Python 对象
loaded_data = json.loads(json_str)
print(f"加载的数据: {loaded_data}") # 输出加载后的数据
# 6. re 库
import re
# 匹配长度为 5 的单词
text = "The quick brown fox jumps over the lazy dog."
pattern = r'\b\w{5}\b' # 正则表达式,匹配长度为5的单词
matches = re.findall(pattern, text) # 查找所有匹配的单词
print(f"匹配的单词: {matches}") # 输出匹配的单词
# 7. collections 库
import collections
# defaultdict
d = collections.defaultdict(int) # 创建一个默认值为int类型的字典
d['apple'] += 1 # 增加'apple'的计数
print(f"defaultdict: {d}") # 输出defaultdict内容
# namedtuple
Point = collections.namedtuple('Point', ['x', 'y']) # 创建一个命名元组
p = Point(10, 20) # 创建一个Point实例
print(f"Point: {p}") # 输出Point的内容
# Counter
counter = collections.Counter('abracadabra') # 计算字符串中每个字符的出现次数
print(f"Counter: {counter}") # 输出Counter结果
# 8. itertools 库
import itertools
# count 示例
for i in itertools.count(start=5, step=2): # 从5开始,每次增加2
if i > 15: # 当i大于15时停止
break
print(f"count: {i}") # 输出当前计数值
# cycle 示例
count = 0
for item in itertools.cycle('AB'): # 循环输出'A'和'B'
if count > 5: # 循环6次后停止
break
print(f"cycle: {item}") # 输出当前项
count += 1
# combinations 示例
comb = list(itertools.combinations('ABCD', 2)) # 获取ABCD中所有长度为2的组合
print(f"combinations: {comb}") # 输出组合结果
# 9. functools 库
import functools
# lru_cache 示例
@functools.lru_cache(maxsize=None) # 使用LRU缓存装饰器
def factorial(n):
if n == 0: # 递归基准条件
return 1
return n * factorial(n - 1) # 递归调用
print(f"Factorial of 5: {factorial(5)}") # 输出5的阶乘
# partial 示例
def power(base, exponent):
return base ** exponent # 计算base的exponent次方
square = functools.partial(power, exponent=2) # 创建一个新的函数,固定参数exponent为2
print(f"Square of 4: {square(4)}") # 输出4的平方
总结
以上是Python常用标准库的介绍和代码示例。这些库极大地丰富了Python的功能,使得数据处理、文件操作、数学计算等任务变得更加简单和高效。在实际开发中,合理利用这些标准库,可以提高代码的可读性和执行效率。