
第十章 知识点总结
学到这里基本上掌握了python的常用操作,但这些还未涉及到数据分析的部分,这些都只是对于语言的灵活运用,至于数据分析,将在后续栏目增加,一起努力学习,未来方向充满不确定,我们能做的就是不断学习,跟随政策,拥抱人工智能,打好地基,方能不被脱节。
目标:掌握 Python 从变量到爬虫的完整技术栈 结构:由浅入深,层层递进,每部分含核心概念 + 示例 + 注意事项
x = 10 # int
x = "hello" # str(合法!)a = [1,2]; b = a → a 和 b 指向同一列表。类型 | 特点 | 示例 |
|---|---|---|
| 数值类型 |
|
| 不可变 Unicode 字符串 |
|
| 布尔值( |
|
| 空值(单例) |
|
listlst = [1, 2, 3]
lst.append(4)
lst[0] = 10tuplet = (1, 2, 3)
t = 1, 2, 3 # 省略括号dictd = {"name": "Alice", "age": 30}
d["city"] = "Beijing"
for k, v in d.items(): ...sets = {1, 2, 3}
s.add(4)
s1 & s2 # 交集💡 关键区别:
listvstuple:是否可变dictvsset:是否有 value
# if-elif-else
if x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")
# for 循环(迭代器协议)
for i in range(5):
print(i)
# while
while n > 0:
n -= 1def greet(name: str, age: int = 18) -> str:
"""文档字符串"""
return f"Hello {name}, you are {age}"
# 调用
greet("Alice") # 位置参数
greet(age=20, name="Bob") # 关键字参数*args(元组)、**kwargs(字典)class Person:
species = "Homo sapiens" # 类属性
def __init__(self, name):
self.name = name # 实例属性
def say_hello(self):
return f"Hi, I'm {self.name}"
p = Person("Alice")
print(p.say_hello())class Student(Person):
def __init__(self, name, student_id):
super().__init__(name)
self.id = student_id
def say_hello(self): # 方法重写
return f"Student: {self.name}"__str__:用户友好字符串__repr__:开发者调试字符串__len__、__getitem__:使对象支持 len()、obj[key]import os
from math import sqrt
from datetime import datetime as dtmypackage/
__init__.py # 标识为包(Python 3.3+ 可省略)
module1.py
subpackage/
__init__.py
module2.pypython -m venv myenv # 创建
source myenv/bin/activate # Linux/macOS
myenv\Scripts\activate # Windows
pip install requests # 安装到虚拟环境# 推荐使用 with(自动关闭)
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
with open('output.txt', 'w') as f:
f.write("Hello")try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input!")
else:
print("Success")
finally:
print("Always run")✅ 最佳实践:不要裸写
except:,应捕获具体异常。
# 列表推导
squares = [x**2 for x in range(10) if x % 2 == 0]
# 生成器(节省内存)
gen = (x**2 for x in range(10))def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start}s")
return result
return wrapper
@timer
def slow_func():
time.sleep(1)class MyFile:
def __enter__(self):
print("Opening file")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Closing file")
with MyFile() as f:
pass模型 | 模块 | 适用场景 |
|---|---|---|
多线程 |
| I/O 密集(网络、磁盘) |
异步 I/O |
| 高并发 I/O(Web 服务) |
多进程 |
| CPU 密集(计算) |
子进程 |
| 调用外部程序 |
⚠️ 记住:Python 有 GIL,多线程不能并行 CPU
socket工具 | 特点 |
|---|---|
| 标准库,功能全但繁琐 |
| 第三方,简洁强大,首选 |
import requests
resp = requests.get("https://api.example.com/data")
data = resp.json()seleniumBeautifulSoupfrom bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
titles = soup.select('h2.title')Scrapy类别 | 标准库 | 第三方库 |
|---|---|---|
时间 |
|
|
JSON |
| — |
正则 |
| — |
日志 |
| — |
单元测试 |
|
|
Web 开发 |
|
|
数据分析 | — |
|
网络请求 |
|
|
爬虫 | — |
|
pathlib 替代 os.path(更面向对象)logging 替代 print 做日志with 管理资源(文件、锁、连接)def f(x=[]) → 改为 x=None''.join(list)encoding='utf-8'verify=False(危险!)requests + BeautifulSoup(静态爬虫)selenium(动态爬虫)asyncio(异步编程)Scrapy(工程化爬虫)基础语法 → 函数/OOP → 文件/异常 → 模块/包
↓
并发模型(threading/asyncio/multiprocessing)
↓
网络编程(socket → urllib → requests)
↓
网页解析(BeautifulSoup / lxml)
↓
动态渲染(selenium)
↓
工程化爬虫(Scrapy)
↓
数据存储(MySQL/MongoDB) + Web服务(FastAPI)💡 核心思想: Python 的优势在于 “胶水语言” + 丰富生态。 不必精通所有细节,但要清楚 每个工具的定位与边界,按需组合,高效解决问题。
这份总结涵盖了从零基础到网络数据获取的完整知识链,建议收藏并结合实践反复巩固。掌握这些,你已具备 Python 中高级开发能力!🚀
公众号:咚咚王
《Python编程:从入门到实践》
《利用Python进行数据分析》
《算法导论中文第三版》
《概率论与数理统计(第四版) (盛骤) 》
《程序员的数学》
《线性代数应该这样学第3版》
《微积分和数学分析引论》
《(西瓜书)周志华-机器学习》
《TensorFlow机器学习实战指南》
《Sklearn与TensorFlow机器学习实用指南》
《模式识别(第四版)》
《深度学习 deep learning》伊恩·古德费洛著 花书
《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》
《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen) 》
《自然语言处理综论 第2版》
《Natural-Language-Processing-with-PyTorch》
《计算机视觉-算法与应用(中文版)》
《Learning OpenCV 4》
《AIGC:智能创作时代》杜雨+&+张孜铭
《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》
《从零构建大语言模型(中文版)》
《实战AI大模型》
《AI 3.0》
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。