以下是Python中10个常规且常用的库:

1. os - 操作系统接口

提供了与操作系统进行交互的功能,例如文件和目录操作、进程管理等。

import os

# 获取当前工作目录
current_dir = os.getcwd()
print(current_dir)

# 创建目录
if not os.path.exists('new_dir'):
    os.mkdir('new_dir')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
2. sys - 系统相关参数和函数

用于访问与Python解释器紧密相关的变量和函数,比如命令行参数处理、标准输入输出等。

import sys

# 获取命令行参数
args = sys.argv
print(args)

# 退出程序
sys.exit()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
3. math - 数学计算

提供了各种数学运算函数,如三角函数、对数函数等。

import math

# 计算平方根
result = math.sqrt(16)
print(result)  # 输出 4.0

# 计算圆周率
pi_value = math.pi
print(pi_value)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
4. random - 生成随机数

用于生成伪随机数,适用于需要随机化的场景,如游戏、模拟等。

import random

# 生成一个0到1之间的随机浮点数
random_float = random.random()
print(random_float)

# 从序列中随机选择一个元素
my_list = [1, 2, 3, 4, 5]
random_choice = random.choice(my_list)
print(random_choice)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
5. datetime - 日期和时间处理

处理日期和时间相关的操作,如获取当前时间、时间差计算等。

import datetime

# 获取当前日期和时间
now = datetime.datetime.now()
print(now)

# 创建指定日期
specific_date = datetime.datetime(2023, 10, 1)
print(specific_date)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
6. json - JSON数据处理

用于编码和解码JSON(JavaScript Object Notation)数据格式,在Web开发中常用于数据传输。

import json

data = {'name': 'John', 'age': 30}

# 将Python对象转换为JSON字符串
json_str = json.dumps(data)
print(json_str)

# 将JSON字符串转换为Python对象
new_data = json.loads(json_str)
print(new_data)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
7. re - 正则表达式

用于处理正则表达式,在文本匹配、搜索和替换等场景非常有用。

import re

text = "The price is $100"
match = re.search(r'\$\d+', text)
if match:
    print(match.group())  # 输出 $100
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
8. collections - 扩展数据类型

提供了一些有用的数据结构,如Counter(用于计数)、defaultdict(具有默认值的字典)等。

from collections import Counter

words = ['apple', 'banana', 'apple', 'cherry', 'banana']
word_count = Counter(words)
print(word_count)  # 输出 Counter({'apple': 2, 'banana': 2, 'cherry': 1})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
9. requests - HTTP请求

用于发送HTTP请求,方便与Web服务进行交互,获取网页内容等。

import requests

response = requests.get('https://www.example.com')
if response.status_code == 200:
    print(response.text)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
10. pandas - 数据处理与分析

主要用于数据处理和分析,提供了高效的数据结构(如DataFrame)和数据分析工具。

import pandas as pd

data = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data)
print(df)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.