从标准库角度深度学习Python

今天给你们带来了从标准库角度学习Python基本用法和实例,Python标准库一般不需要额外安装,安装Python时候已经有了。

1. math库:进行数学运算

import math``# 计算平方根``x = math.sqrt(25)``print(x)``# 计算正弦值``y = math.sin(math.pi/2)``print(y)
输出:``5.0``1.0

2. random 库:生成随机数

import random``# 生成0到1之间的随机浮点数``x = random.random()``print(x)``# 生成指定范围内的随机整数``y = random.randint(1, 10)``print(y)
输出:``0.6520157672107111``1

3. datetime 库:处理日期和时间

import datetime``# 获取当前日期和时间``x = datetime.datetime.now()``print(x)``# 格式化日期和时间``y = x.strftime("%Y-%m-%d %H:%M:%S")``print(y)
输出:``2023-11-01 01:34:29.186145``2023-11-01 01:34:29

4. json 库:处理 JSON 数据

import json``# JSON 编码``x = json.dumps({"name": "Alice", "age": 25})``print(x)``# JSON 解码``y = json.loads('{"name": "Bob", "age": 30}')``print(y)
输出:``{"name": "Alice", "age": 25}``{'name': 'Bob', 'age': 30}

5. csv 库:读写 CSV 文件

`import csv``# 写入 CSV 文件``with open('data.csv', 'w', newline='') as file:`    `writer = csv.writer(file)`    `writer.writerow(['Name', 'Age'])`    `writer.writerow(['Alice', 25])``# 读取 CSV 文件``with open('data.csv', 'r') as file:`    `reader = csv.reader(file)`    `for row in reader:`        `print(row)``   `‍
输出:``['Name', 'Age']``['Alice', '25']

6. os 库:操作系统交互

import os``# 获取当前工作目录``x = os.getcwd()``print(x)``# 创建目录``os.mkdir('new_directory')
输出:``C:\Users\Administrator\Desktop

7. sys 库:访问和控制 Python 解释器

import sys``# 获取命令行参数``x = sys.argv``print(x)``# 退出程序``sys.exit(0)
输出:``['C:\\Users\\Administrator\\Desktop\\s.py']

8. re库:正则表达式匹配和操作

import re``# 查找与模式匹配的字符串``x = re.findall(r'\b[Aa]\w+\b', 'A quick brown fox jumps over the lazy dog.')``print(x)``# 替换字符串``y = re.sub(r'\b\d+\b', 'NUM', 'There are 123 cats.')``print(y)
输出:``[]``There are NUM cats.

9. urllib 库:进行 URL 相关操作

import urllib.request``# 发送 HTTP 请求``response = urllib.request.urlopen('http://www.example.com')``html = response.read()``print(html)
输出:``b'<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset="utf-8" />\n    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />\n    <meta name="viewport" content="width=device-width, initial-scale=1" />\n    <style type="text/css">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 2em;\n        background-color: #fdfdff;\n        border-radius: 0.5em;\n        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        div {\n            margin: 0 auto;\n            width: auto;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is for use in illustrative examples in documents. You may use this\n    domain in literature without prior coordination or asking for permission.</p>\n    <p><a href="https://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>\n'``   

10. sqlite3 库:操作 SQLite 数据库

import sqlite3``# 连接数据库``conn = sqlite3.connect('example.db')``# 创建表``conn.execute('CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)')``# 插入数据``conn.execute('INSERT INTO users VALUES (?, ?)', ('Alice', 25))``# 查询数据``cursor = conn.execute('SELECT * FROM users')``for row in cursor:`    `print(row)``# 关闭数据库连接``conn.close()
输出:``('Alice', 25)

11. gzip 库:进行 gzip 压缩和解压缩

import gzip``# 压缩文件``with open('file.txt', 'rb') as f_in, gzip.open('file.txt.gz', 'wb') as f_out:`    `f_out.writelines(f_in)``# 解压缩文件``with gzip.open('file.txt.gz', 'rb') as f_in, open('file.txt', 'wb') as f_out:`    `f_out.writelines(f_in)

12. pickle 库:对象的序列化和反序列化

import pickle``# 序列化对象``data = {'name': 'Alice', 'age': 25}``with open('data.pkl', 'wb') as file:`    `pickle.dump(data, file)``# 反序列化对象``with open('data.pkl', 'rb') as file:`    `data = pickle.load(file)``print(data)
输出:``{'name': 'Alice', 'age': 25}

13. subprocess库:执行外部命令和进程管理

import subprocess``# 执行外部命令``result = subprocess.run(['ls', '-l'], capture_output=True, text=True)``print(result.stdout)``# 启动子进程``subprocess.Popen(['python', 'script.py'])

14.collections 库:提供了额外的数据结构,如deque和Counter

from collections import deque, Counter``   ``# 使用deque实现队列``queue = deque()``queue.append(1)``queue.append(2)``queue.append(3)``print(queue.popleft())``   ``# 使用Counter统计元素频率``c = Counter(['apple', 'banana', 'apple', 'orange'])``print(c['apple'])
输出:``1``2

15.itertools 库:提供了用于迭代操作的函数,如排列组合和无限迭代

import itertools``# 获取迭代器的排列组合``perms = itertools.permutations(['a', 'b', 'c'], 2)``for perm in perms:`    `print(perm)``# 无限迭代器``count = itertools.count(start=0, step=2)``print(next(count))``print(next(count))
输出:``('a', 'b')``('a', 'c')``('b', 'a')``('b', 'c')``('c', 'a')``('c', 'b')``0``2``   

16.logging 库:用于记录日志信息

import logging``# 设置日志记录级别``logging.basicConfig(level=logging.INFO)``# 输出日志``logging.debug('This is a debug message.')``logging.info('This is an info message.')

**17.**time 库:提供时间相关的函数

import time``# 获取当前时间戳``print(time.time())``# 睡眠一秒``time.sleep(1)
输出;1698775155.747288

18.glob 库:用于查找文件路径模式匹配的文件列表

import glob``# 查找文件``files = glob.glob('*.txt')``for file in files:`    `print(file)
输出:``profile_output.txt``新建文本文档 (2).txt``新建文本文档.txt

19.shutil 库:高级文件操作功能

import shutil``# 复制文件``shutil.copy('source.txt', 'destination.txt')``# 移动文件夹``shutil.move('folder', 'new_folder')

20.hashlib 库:提供了常见的哈希函数,如MD5和SHA

import hashlib``# 计算字符串的MD5哈希值``hash_object = hashlib.md5(b'Hello World')``print(hash_object.hexdigest())
输出:``b10a8db164e0754105b7a99be72e3fe5

21.socket 库:进行网络编程

import socket``# 创建TCP套接字``s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)``s.connect(('www.example.com', 80))``# 发送HTTP请求``s.sendall(b'GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n')``response = s.recv(4096)``print(response.decode('utf-8'))``# 关闭套接字``s.close()
输出:``HTTP/1.1 200 OK``Age: 578050``Cache-Control: max-age=604800``Content-Type: text/html; charset=UTF-8``Date: Tue, 31 Oct 2023 18:05:34 GMT``Etag: "3147526947+gzip+ident"``Expires: Tue, 07 Nov 2023 18:05:34 GMT``Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT``Server: ECS (sac/2569)``Vary: Accept-Encoding``X-Cache: HIT``Content-Length: 1256``   ``<!doctype html>``<html>``<head>`    `<title>Example Domain</title>``   `    `<meta charset="utf-8" />`    `<meta http-equiv="Content-type" content="text/html; charset=utf-8" />`    `<meta name="viewport" content="width=device-width, initial-scale=1" />`    `<style type="text/css">`    `body {`        `background-color: #f0f0f2;`        `margin: 0;`        `padding: 0;`        `font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;``   `    `}`    `div {`        `width: 600px;`        `margin: 5em auto;`        `padding: 2em;`        `background-color: #fdfdff;`        `border-radius: 0.5em;`        `box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);`    `}`    `a:link, a:visited {`        `color: #38488f;`        `text-decoration: none;`    `}`    `@media (max-width: 700px) {`        `div {`            `margin: 0 auto;`            `width: auto;`        `}`    `}``</style>``</head>``   ``<body>``<div>`    `<h1>Example Domain</h1>`    `<p>This domain is for use in illustrative examples in documents. You may use this`    `domain in literature without prior coordination or asking for permission.</p>`    `<p><a href="https://www.iana.org/domains/example">More information...</a></p>``</div>``</body>``</html>

22.unittest 库:用于编写单元测试

import unittest``# 编写测试类``class MyTestCase(unittest.TestCase):`    `def test_addition(self):`        `self.assertEqual(1 + 2, 3)``# 运行测试``unittest.main()
----------------------------------------------------------------------``Ran 1 test in 0.000s``   ``OK

以上就是“从标准库角度深度学习Python”的全部内容,希望对你有所帮助。

关于Python技术储备

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

在这里插入图片描述

二、Python必备开发工具

img

三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

img

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

img

五、Python练习题

检查学习结果。

img

六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

img

最后祝大家天天进步!!

上面这份完整版的Python全套学习资料已经上传至CSDN官方,朋友如果需要可以直接微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值