python 常用的第三方模块
一、requests模块
1. 简介
-
被称为requests库,是用于处理HTTP(Hypertext Transfer Protocol超文本传输协议)请求的第三方库,该库在爬虫程序中应用非常广泛。
-
使用requests库中的
get()函数
可以打开一个网络请求,并获取一个Response响应对象。响应结果中的字符串数据
可以通过响应对象的text属性
获取,响应结果中除了有字符串数据也有二进制数据
,响应结果中的二进制数据可以通过响应对象的content属性
获取
2. 环境准备
确保已安装 requests
模块。如果未安装,可以通过以下命令安装:
pip install requests
3. 示例代码
3.1 爬取天气信息
以下代码展示了如何使用 requests
和正则表达式爬取天气信息。
import requests
import re
def fetch_weather():
# 爬虫目标网页
url = "https://www.weather.com.cn/weather1d/101010100.shtml"
# 发起 GET 请求
response = requests.get(url)
# 设置编码格式为 UTF-8
response.encoding = 'utf-8'
# 使用正则表达式提取所需内容
city = re.findall('<span class="name">([\u4e00-\u9fa5]*)</span>', response.text)
weather = re.findall('<span class="weather">([\u4e00-\u9fa5]*)</span>', response.text)
temperature = re.findall('<span class="wd">(.*)</span>', response.text)
travel_index = re.findall('<span class="zs">([\u4e00-\u9fa5]*)</span>', response.text)
# 将提取的数据组合成列表
data = list(zip(city, weather, temperature, travel_index))
# 打印提取的数据
for item in data:
print(item)
---------------
['三亚', '多云', '20/28℃', '适宜']
['九寨沟', '晴', '4/27℃', '适宜']
['大理', '多云转小雨', '11/22℃', '适宜']
['张家界', '晴转阴', '11/32℃', '适宜']
['桂林', '多云', '13/31℃', '适宜']
['青岛', '多云', '9/15℃', '一般']
-
requests.get(url)
:发送 GET 请求,获取网页内容。 -
response.encoding = 'utf-8'
:设置响应内容的编码格式为 UTF-8,确保中文字符能正确显示。 -
re.findall()
:使用正则表达式提取网页中的特定内容。 -
zip()
:将多个列表组合成一个列表,方便后续处理。
3.2 爬取并保存图片
以下代码展示了如何使用 requests
爬取图片并保存到本地。
import requests
def fetch_image():
# 爬虫目标图片 URL
url = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"
# 发起 GET 请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 以二进制写入模式保存图片
with open('logo.png', 'wb') as file:
file.write(response.content)
print("图片下载并保存成功!")
else:
print("图片下载失败,状态码:", response.status_code)
---------------
开始爬取百度 logo 图片...
图片下载并保存成功!
-
requests.get(url)
:发送 GET 请求,获取图片内容。 -
response.status_code
:检查请求是否成功(状态码为 200 表示成功)。 -
with open('logo.png', 'wb') as file
:以二进制写入模式打开文件,确保图片数据正确保存。
二、openpyxl模块
1. 简介
- openpyxl 是一个用于读写 Excel 2010 xlsx/xlsm/xltx/xltm 文件的 Python 库。它提供了丰富的功能,可以方便地操作 Excel 文件,包括创建、读取、修改和保存。
函数/属性名称 | 功能描述 |
---|---|
load workbook(filename) | 打开已存在的表格,结果为工作簿对象 |
workbook.sheetnames | 工作簿对象的sheetnames属性,用于获取所有工作表的名称,结果为列表类型 |
sheet.append(lst) | 向工作表中添加一行数据,新数据接在工作表已有类据的后面 |
workbook.save(excelname) | 保存工作簿 |
Workbook() | 创建新的工作簿对象 |
2. 环境准备
- 确保已安装
openpyxl
模块。如果未安装,可以通过以下命令安装:
pip install openpyxl
3. 示例代码及详细解释
3.1 创建 Excel 文件并写入数据
- 模块weather:
import requests
import re
def fetch_weather():
# 爬虫目标网页
url = "https://www.weather.com.cn/weather1d/101010100.shtml"
# 发起 GET 请求
response = requests.get(url)
# 设置编码格式为 UTF-8
response.encoding = 'utf-8'
# 使用正则表达式提取所需内容
city = re.findall('<span class="name">([\u4e00-\u9fa5]*)</span>', response.text)
weather = re.findall('<span class="weather">([\u4e00-\u9fa5]*)</span>', response.text)
temperature = re.findall('<span class="wd">(.*)</span>', response.text)
travel_index = re.findall('<span class="zs">([\u4e00-\u9fa5]*)</span>', response.text)
# 将提取的数据组合成列表
data = list(zip(city, weather, temperature, travel_index))
return data
- 创建 Excel 文件并写入数据
import openpyxl
from openpyxl.workbook import Workbook
# 假设从 weather 模块中获取天气数据
import weather
lst = weather.fetch_weather() # 获取天气数据
# 创建一个新的 Excel 工作簿
workbook = openpyxl.Workbook() # 创建工作簿对象
# 创建工作表
sheet = workbook.create_sheet('travel') # 创建名为 'travel' 的工作表
# 向工作表中添加数据
for item in lst:
sheet.append(item) # 一次添加一行
# 保存工作簿
workbook.save('travel.xlsx')
print("数据已成功写入 'travel.xlsx' 文件中")
3.2 从 Excel 文件中读取数据
# 打开已存在的 Excel 工作簿
workbook1 = openpyxl.load_workbook('travel.xlsx')
# 选择要操作的工作表
sheet1 = workbook1['travel'] # 选择名为 'travel' 的工作表
# 读取工作表中的数据
lst1 = [] # 用于存储表格数据
for row in sheet1.rows: # 遍历每一行
sublst = [] # 用于存储当前行的数据
for cell in row: # 遍历当前行的每个单元格
sublst.append(cell.value) # 将单元格的值添加到子列表中
lst1.append(sublst) # 将当前行的数据添加到总列表中
# 打印读取的数据
for item in lst1:
print(item)
----------------
['景区', '天气', '气温', '旅游指数']
['三亚', '多云', '20/28℃', '适宜']
['九寨沟', '晴', '4/27℃', '适宜']
['大理', '多云转小雨', '11/22℃', '适宜']
['张家界', '晴转阴', '11/32℃', '适宜']
['桂林', '多云', '13/31℃', '适宜']
['青岛', '多云', '9/15℃', '一般']
三、pdfplumber模块
1. 简介
pdfplumber
是一个基于pdfminer.six
的 Python 库,专门用于从 PDF 文件中提取文本、表格和其他信息。它提供了简单而强大的接口,能够精确解析 PDF 页面布局,适合处理包含复杂布局或多列文本的 PDF 文件。
2. 安装
pip install pdfplumber
3、基本功能
3.1 打开 PDF 文件
import pdfplumber
with pdfplumber.open("example.pdf") as pdf:
print(f"PDF 文档包含 {len(pdf.pages)} 页")
pdfplumber.open()
方法用于加载 PDF 文件,pdf.pages
是一个列表,包含 PDF 中的每一页。
3.2 提取页面中的文本
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
text = page.extract_text()
print("第一页文本内容:")
print(text)
with pdfplumber.open('example.pdf') as pdf:
for i in pdf.pages:
print(i.extract_text()) # extract_test()方法提取内容
print(f'-------第{i.page_number}页结束')
page.extract_text()
方法可以提取页面中的纯文本内容。如果 PDF 中的文本格式较为复杂,该方法能够较好地保持文本的布局。
3.3 提取表格数据
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
table = page.extract_table()
print("表格内容:")
for row in table:
print(row)
page.extract_table()
方法可以提取页面中的表格数据,并将其解析为嵌套列表,其中每一行是一个列表。如果页面中有多个表格,可以使用 page.extract_tables()
方法。
3.4 获取图像信息
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
for img in page.images:
print(f"图片信息:{img}")
page.images
返回一个列表,包含页面中所有图像的详细信息,例如位置和尺寸。
3.5 分析页面布局
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
words = page.extract_words()
lines = page.lines
rects = page.rects
print(f"文本框数量:{len(words)}")
print(f"线条数量:{len(lines)}")
print(f"矩形数量:{len(rects)}")
page.extract_words()
提取页面中的文本框,page.lines
获取页面中的线条,page.rects
获取矩形。
4、高级功能
4.1 提取特定区域的内容
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
cropped = page.within_bbox((0, 0, 500, 100)) # 提取页面顶部区域
text = cropped.extract_text()
print("页面顶部的文本:")
print(text)
通过 page.within_bbox()
方法可以指定页面中的一个矩形区域,然后对该区域进行操作。
4.2 导出页面为图片
from PIL import Image
with pdfplumber.open("example.pdf") as pdf:
page = pdf.pages[0]
page_image = page.to_image(resolution=150) # 分辨率 150 DPI
page_image.save("page_image.png")
page.to_image()
方法可以将页面导出为图片,方便进一步处理。
4.3 搜索特定文本
import pdfplumber
import re
def search_text(pdf_path, search_term):
with pdfplumber.open(pdf_path) as pdf:
results = []
for i, page in enumerate(pdf.pages):
text = page.extract_text()
matches = re.finditer(search_term, text, re.IGNORECASE)
for match in matches:
results.append({
'page': i + 1,
'text': match.group(),
'position': match.start()
})
return results
pdf_path = "example.pdf"
search_term = "Python"
search_results = search_text(pdf_path, search_term)
for result in search_results:
print(f"Found '{result['text']}' on page {result['page']} at position {result['position']}")
使用正则表达式可以在 PDF 文档中搜索特定文本。
5、应用场景
pdfplumber
适用于以下场景:
- 文本提取:从报告、文档等 PDF 文件中提取文本内容。
- 表格解析:从财务报表、研究文档等 PDF 文件中提取表格数据。
- 数据分析:将提取的文本和表格数据用于进一步的数据分析。
四、NumPy 模块
1. NumPy 简介
- 安装:
pip install numpy
- 用途:NumPy 是 Python 中用于科学计算的一个基础库,广泛应用于数据分析、机器学习等领域。它提供了强大的多维数组对象(
ndarray
)以及大量的操作这些数组的函数,是许多其他库(如 Pandas、Matplotlib 等)的依赖库。
2. 常用方法整理
2.1 创建数组
-
np.array()
:从 Python 列表或其他序列创建 NumPy 数组。import numpy as np a = np.array([1, 2, 3]) # 一维数组 b = np.array([[1, 2, 3], [4, 5, 6]]) # 二维数组
-
np.zeros()
:创建指定形状的全零数组。zeros_array = np.zeros((3, 4)) # 3 行 4 列的全零数组
-
np.ones()
:创建指定形状的全一数组。ones_array = np.ones((2, 3)) # 2 行 3 列的全一数组
-
np.arange()
:创建等差数列数组。range_array = np.arange(0, 10, 2) # 从 0 到 10,步长为 2
-
np.linspace()
:创建等间隔数列数组。linspace_array = np.linspace(0, 10, 5) # 从 0 到 10,生成 5 个等间隔的数
2.2 数组属性
-
shape
:获取数组的形状(维度和大小)。print(a.shape) # 输出 (3,) print(b.shape) # 输出 (2, 3)
-
dtype
:获取数组的数据类型。print(a.dtype) # 输出 int64
-
ndim
:获取数组的维度。print(a.ndim) # 输出 1 print(b.ndim) # 输出 2
2.3 数组操作
-
索引与切片:
print(a[1]) # 输出 2 print(b[1, 2]) # 输出 6 print(b[0, :]) # 输出 [1, 2, 3]
-
数组运算:
c = np.array([1, 2, 3]) d = np.array([4, 5, 6]) print(c + d) # 输出 [5, 7, 9] print(c * d) # 输出 [4, 10, 18]
-
点乘运算:
e = np.array([[1, 2], [3, 4]]) f = np.array([[5, 6], [7, 8]]) print(np.dot(e, f)) # 矩阵乘法
2.4 数组统计方法
-
np.sum()
:计算数组元素的总和。print(np.sum(a)) # 输出 6
-
np.mean()
:计算数组元素的平均值。print(np.mean(a)) # 输出 2.0
-
np.max()
:计算数组元素的最大值。print(np.max(a)) # 输出 3
-
np.min()
:计算数组元素的最小值。print(np.min(a)) # 输出 1
2.5 数组重塑
-
reshape()
:改变数组的形状。g = np.array([1, 2, 3, 4, 5, 6]) reshaped_array = g.reshape(2, 3) # 将数组重塑为 2 行 3 列
2.6 随机数生成
-
np.random.rand()
:生成指定形状的随机数组(值在 [0, 1) 之间)。random_array = np.random.rand(3, 4)
-
np.random.randint()
:生成指定范围内的随机整数数组。random_int_array = np.random.randint(0, 10, size=(2, 3))
3. 应用示例:图像灰度处理
import matplotlib.pyplot as plt
import numpy as np
# 读取图像
n1 = plt.imread('logo.jpg')
print(type(n1), n1.shape) # 输出数组类型和形状
# 显示原始图像
plt.imshow(n1)
plt.title("Original Image")
plt.show()
# 灰度处理公式
n2 = np.array([0.299, 0.587, 0.114]) # RGB 到灰度的权重
# 将数组 1(RGB)颜色值与数组n2(灰度公式固定值),进行点乘运算
x = np.dot(n1, n2)
# 显示灰度图像
plt.imshow(x, cmap='gray')
plt.title("Grayscale Image")
plt.show()
4. 总结
NumPy 提供了高效的数据结构和丰富的操作方法,是 Python 数据分析和科学计算的核心工具之一。掌握其常用方法可以帮助我们高效地处理数组和矩阵数据。
五、Pandas 模块
1、什么是 Pandas?
Pandas 是基于 NumPy 构建的强大数据分析工具,提供了灵活、快速的数据结构和数据处理函数,是数据分析与科学计算中不可或缺的工具之一。
📦 安装方式:
pip install pandas
📚 导入模块:
import pandas as pd
2、Pandas 两大核心数据结构
类型 | 描述 | 类似结构 |
---|---|---|
Series |
一维带标签的数组 | 列表 / 一维数组 |
DataFrame |
二维表格型数据结构 | 表格 / Excel |
2.1 Series(带索引的一维数组)
✅ 创建方式:
import pandas as pd
s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])
print(s)
🎯 常用操作:
# s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])
print(s['b']) # 访问某个值 20
print(s[1:3]) # 切片b 20 c 30 dtype: int64
print(s.mean()) # 平均值 25.0
print(s.sum()) # 求和 100
print(s.max()) # 最大值 40
print(s.idxmax()) # 最大值对应的索引 d
2.2 DataFrame(带行列标签的二维表)
✅ 创建方式:
data = {
'姓名': ['张三', '李四', '王五'],
'年龄': [20, 25, 22],
'成绩': [88, 92, 95]
}
df = pd.DataFrame(data)
print(df)
📋 输出示例:
姓名 年龄 成绩
0 张三 20 88
1 李四 25 92
2 王五 22 95
3、DataFrame 常用方法与操作大全
3.1 基本信息查看
df.head() # 查看前5行
df.tail(2) # 查看最后2行
df.shape # 行列数(元组)
df.info() # 数据类型 & 缺失值
df.describe() # 快速统计(数值型)
df.columns # 所有列名
df.index # 行索引
3.2 选择与筛选数据
df['姓名'] # 取某列(Series)
df[['姓名', '成绩']] # 多列(DataFrame)
df.iloc[0] # 按位置取第一行
df.loc[0] # 按标签取第一行
df[df['成绩'] > 90] # 条件筛选
3.3 数据增删改查
✅ 添加列:
df['性别'] = ['男', '女', '男']
✅ 修改值:
df.at[1, '成绩'] = 95 # 修改单元格值
✅ 删除列或行:
df.drop('性别', axis=1) # 删除列(不改变原数据)
df.drop(1, axis=0) # 删除第2行
df.drop(columns=['成绩']) # 多列删除
3.4 排序与分组
df.sort_values('成绩', ascending=False) # 按成绩降序排序
df.sort_index() # 按行索引排序
df.groupby('性别')['成绩'].mean() # 分组统计平均分
3.5 缺失值处理
df.isnull() # 是否缺失
df.dropna() # 删除含缺失值的行
df.fillna(0) # 缺失填 0
df['成绩'].fillna(df['成绩'].mean()) # 用平均数填充
4、导入与导出文件
✅ 读取文件
pd.read_csv('data.csv')
pd.read_excel('data.xlsx')
✅ 保存文件
df.to_csv('output.csv', index=False)
df.to_excel('output.xlsx', index=False)
5、练习建议与学习路径
- 用 CSV 文件进行练习(建议 Excel 导出为 CSV)
- 实践中反复使用
head()
、info()
、describe()
等方法 - 理解索引操作
iloc
与loc
的区别 - 利用
groupby()
进行分组分析 - 了解
merge()
、concat()
做数据拼接(进阶)
6、附:常用方法速查表
目的 | 方法示例 |
---|---|
查看数据 | df.head() , df.info() |
选列选行 | df['列'] , df.loc[] , df.iloc[] |
排序 | df.sort_values() , sort_index() |
缺失值处理 | dropna() , fillna() |
导入导出 | read_csv() , to_excel() |
分组统计 | groupby().mean() 等 |
六、Matplotlib 模块
- Matplotlib是用于数据可视化的模块,使用Matplotlib.pyplot可以非常方便的绘制饼图、柱形图、折线图等
1. 安装与导入
pip install matplotlib
import matplotlib.pyplot as plt
2. 常用绘图方法
-
绘制折线图:
import matplotlib.pyplot as plt # 定义 x 和 y 的数据 x = [1, 2, 3, 4, 5] # 横坐标数据 y = [2, 3, 5, 7, 11] # 纵坐标数据 # 绘制折线图 plt.plot(x, y, label='Line 1', color='blue', linestyle='--') # 添加图例、颜色和线型 plt.xlabel('X-axis') # 设置 X 轴标签 plt.ylabel('Y-axis') # 设置 Y 轴标签 plt.title('Line Plot') # 设置标题 plt.legend() # 显示图例 plt.show()
-
绘制柱状图:
import matplotlib.pyplot as plt # 定义 x 和 y 的数据 x = [1, 2, 3, 4, 5] # 横坐标数据 y = [2, 3, 5, 7, 11] # 纵坐标数据 plt.bar(x, y, color='green', width=0.5) # 设置柱状图颜色和宽度 plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Bar Chart') plt.show()
-
绘制饼图:
import matplotlib.pyplot as plt # 定义数据 x = ['A', 'B', 'C'] # 标签 y = [25, 35, 40] # 数值数据 # 定义颜色列表 colors = ['red', 'green', 'blue'] # 绘制饼图 plt.pie(y, labels=x, autopct='%1.1f%%', startangle=90, colors=colors) # 添加标题 plt.title('Pie Chart') # 显示图形 plt.show()
-
绘制散点图:
import matplotlib.pyplot as plt # 定义数据 x = ['A', 'B', 'C'] # 标签 y = [25, 35, 40] # 数值数据 plt.scatter(x, y, color='purple', marker='o') # 设置散点图颜色和标记 plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Scatter Plot') plt.show()
3. 图形样式设置
-
设置字体:
plt.rcParams['font.sans-serif'] = ['SimSun'] # 设置中文字体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
-
设置图形大小:
plt.figure(figsize=(10, 6)) # 设置图形窗口大小
-
设置坐标轴:
plt.axis('equal') # 设置坐标轴比例相等 plt.xlim(0, 10) # 设置 X 轴范围 plt.ylim(0, 100) # 设置 Y 轴范围 plt.xticks([0, 2, 4, 6, 8, 10]) # 设置 X 轴刻度 plt.yticks([0, 20, 40, 60, 80, 100]) # 设置 Y 轴刻度
4. 多图绘制
-
子图布局:
fig, ax = plt.subplots(2, 2, figsize=(10, 8)) # 创建 2x2 的子图布局 ax[0, 0].plot(x, y) ax[0, 1].bar(x, y) ax[1, 0].scatter(x, y) ax[1, 1].pie(y, labels=x) plt.tight_layout() # 自动调整子图间距 plt.show()
5. 保存图形
plt.savefig('figure.png', dpi=300) # 保存为 PNG 图片,设置分辨率
示例代码
结合 Pandas 和 Matplotlib 的常用功能:
import pandas as pd
import matplotlib.pyplot as plt
# pd.read_excel():从 Excel 文件中读取数据。
df = pd.read_excel('python.xlsx')
print(df)
# 解决中文乱码 # SimSun 确保计算机中有这个字体 字体位置:C:\Windows\Fonts
# 'font.sans-serif' 是配置参数的键,表示设置无衬线字体。
plt.rcParams['font.sans-serif']=['SimSun']
# 设置画布的大小
# plt.figure():创建一个新的图形窗口。参数 figsize=(10, 6):设置图形窗口的大小,单位为英寸。这里设置宽度为 10 英寸,高度为 6 英寸
plt.figure(figsize=(10,6))
label = df["系统"]
y = df['告警数量']
# print(labels)
# print(y)
# plt.pie():绘制饼图
plt.pie(y,labels=label,autopct='%1.1f%%',startangle=90)
# 参数 y:表示饼图的数值数据。
# 参数 labels=label:设置饼图的标签(扇区名称),这里使用 label 中的值。
# 参数 autopct='%1.1f%%':设置饼图中每个扇区的百分比显示格式,%1.1f%% 表示保留一位小数的百分比。
# 参数 startangle=90:设置饼图的起始角度,这里从 90 度开始绘制(即从正上方开始)
# 设置x,y轴刻度
# plt.axis():设置坐标轴的属性。
plt.axis('equal') # 参数 'equal':表示设置坐标轴的比例相等,确保饼图是一个标准的圆形,而不是椭圆形。
# plt.title():设置图形的标题。
plt.title('告警主机数量系统占比图')
# plt.show():显示绘制的图表。
plt.show()
七、PyEcharts模块
-
PyEcharts是由百度开源的数据可视化库,它对流行图的支持度比较高,它给用户提供了30多种图形,如柱形渐变图
K线周期图等 -
PyEcharts的使用可以分四个步骤实现:
1.导入pyecharts包
2.找到相应图形模板
3.准备相应数据
4.对图表进行个性化修饰
示例
# 导入模块
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
# 实例:
# c = (
# Pie()
# .add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
# .set_global_opts(title_opts=opts.TitleOpts(title="Pie-基本示例"))
# .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
# .render("pie_base.html")
# )
# 数据
# print([list(z) for z in zip(Faker.choose(), Faker.values())])
# [['可乐', 130], ['雪碧', 50], ['橙汁', 147], ['绿茶', 149], ['奶茶', 105], ['百威', 29], ['青岛', 32]]
# 自定义修改
lst = [['ubuntu',20],['centos',49],['windows',36]]
c = (
Pie()
.add("", lst)
.set_global_opts(title_opts=opts.TitleOpts(title="OS"))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.render("OS.html")
)
- 代码复制修改
八、PIL(Pillow)模块
1. 简介
Pillow 是 Python Imaging Library(PIL)的一个分支,用于图像处理,支持图像存储、处理和显示等操作。
2. 安装
pip install pillow
3. 常用方法及示例
3.1 图像加载与保存
from PIL import Image
# 加载图片
im = Image.open('logo.jpg')
print(type(im), im)
# 保存图片
im.save('output.jpg')
3.2 分离与合并通道
# 分离通道
r, g, b = im.split()
# 合并通道
om1 = Image.merge(mode='RGB', bands=(r, b, g))
om1.save('new1.jpg')
3.3 图像裁剪
# 裁剪图像,参数为左上角坐标和右下角坐标
cropped_im = im.crop((10, 10, 100, 100))
cropped_im.save('cropped.jpg')
3.4 图像缩放
# 缩放图像
resized_im = im.resize((200, 200))
resized_im.save('resized.jpg')
3.5 图像旋转
# 旋转图像
rotated_im = im.rotate(90)
rotated_im.save('rotated.jpg')
3.6 图像滤镜
from PIL import ImageFilter
# 应用模糊滤镜
blurred_im = im.filter(ImageFilter.BLUR)
blurred_im.save('blurred.jpg')
4. 应用场景
- 图像编辑软件:用于裁剪、缩放、旋转等基本操作。
- 图像识别系统:对图像进行预处理,如灰度化、二值化等。
- 网站开发:动态生成缩略图、水印等。
九、jieba模块
1. 简介
jieba 是 Python 中用于中文分词的模块,可以将一段中文文本分隔成中文词组的序列。
2. 安装
pip install jieba
3. 常用方法及示例
3.1 基本分词
import jieba
# 分词
text = "我爱自然语言处理"
words = jieba.lcut(text)
print(words)
3.2 添加自定义词典
# 添加自定义词典
jieba.load_userdict('userdict.txt')
# 分词
text = "我爱自然语言处理"
words = jieba.lcut(text)
print(words)
3.3 关键词提取
import jieba.analyse
# 提取关键词
text = "我爱自然语言处理,因为它很有趣。"
keywords = jieba.analyse.extract_tags(text, topK=3)
print(keywords)
3.4 词性标注
import jieba.posseg as pseg
# 词性标注
text = "我爱自然语言处理"
words = pseg.cut(text)
for word, flag in words:
print(f"{word} {flag}")
4. 应用场景
- 文本分析:对中文文本进行分词、关键词提取等操作。
- 搜索引擎:对用户输入的查询进行分词,提高搜索精度。
- 自然语言处理:作为文本预处理工具,用于后续的文本分类、情感分析等任务。
十、PyInstaller模块
1. 简介
PyInstaller 是一个第三方库,可以将 Python 源文件打包成可执行文件。支持 Windows、Linux 和 Mac OS 操作系统。
2. 安装
pip install pyinstaller
3. 常用方法及示例
3.1 基本打包
# 打包单个文件
pyinstaller -F game.py
3.2 打包带依赖文件
# 打包时指定图标
pyinstaller --icon=icon.ico -F game.py
# 打包时指定输出目录
pyinstaller --distpath=dist_output -F game.py
3.3 打包为单文件
# 打包为单文件
pyinstaller --onefile game.py
4. 注意事项
- 打包文件路径尽量避免包含中文,否则可能导致打包失败。
- 如果项目依赖外部文件(如配置文件、图片等),需要使用
--add-data
参数指定路径。
5. 应用场景
- 分发 Python 应用程序:将 Python 脚本打包为可执行文件,方便在没有 Python 环境的机器上运行。
- 创建桌面应用程序:将 Python 项目打包为独立的可执行文件,便于用户使用。
十一、prettytable模块
1.简介
- 定义:
prettytable
是一个 Python 库,用于在终端或控制台中生成美观的表格格式输出。 - 特点:
-
支持自定义表格样式,包括列对齐方式、边框样式等。
-
可以方便地添加、删除和修改表格中的数据。
-
支持将表格数据导出为多种格式(如 HTML、CSV 等)。
-
适用于数据展示、日志记录、测试结果输出等场景。
-
2.安装
pip install prettytable
3.常用方法
-
创建表格:
-
使用
PrettyTable()
创建一个空表格对象。table = PrettyTable()
-
-
设置表头:
-
使用
field_names
属性设置表格的列名(表头)。table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
-
-
添加行数据:
-
使用
add_row()
方法向表格中添加一行数据。table.add_row(["Adelaide", 1295, 1158259, 600.5])
-
-
添加多行数据:
-
使用
add_rows()
方法一次性添加多行数据。rows = [ ["Adelaide", 1295, 1158259, 600.5], ["Darwin", 112, 120900, 1714.7], ["Sydney", 2058, 4336374, 1214.8] ] table.add_rows(rows)
-
-
设置列对齐方式:
-
使用
align
属性设置列的对齐方式,可选值为"l"
(左对齐)、"c"
(居中对齐)、"r"
(右对齐)。table.align["City name"] = "l" table.align["Area"] = "r" table.align["Population"] = "c"
-
-
设置表格边框样式:
-
使用
border
属性设置是否显示表格边框,默认为True
。table.border = False
-
-
设置列宽:
-
使用
max_width
属性设置列的最大宽度。table.max_width = 10
-
-
删除行:
-
使用
del_row()
方法删除指定行。table.del_row(0) # 删除第一行
-
-
清空表格:
-
使用
clear_rows()
方法清空表格中的所有行数据。table.clear_rows()
-
-
导出表格为其他格式:
-
将表格导出为 HTML 格式:
html_table = table.get_html_string() with open("table.html", "w") as f: f.write(html_table)
-
将表格导出为 CSV 格式:
csv_table = table.get_csv_string() with open("table.csv", "w") as f: f.write(csv_table)
-
4.示例
-
示例 1:创建并打印一个简单的表格
from prettytable import PrettyTable table = PrettyTable() table.field_names = ["City name", "Area", "Population", "Annual Rainfall"] table.add_row(["Adelaide", 1295, 1158259, 600.5]) table.add_row(["Darwin", 112, 120900, 1714.7]) table.add_row(["Sydney", 2058, 4336374, 1214.8]) print(table)
输出:
+-----------+------+------------+---------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+---------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Darwin | 112 | 120900 | 1714.7 | | Sydney | 2058 | 4336374 | 1214.8 | +-----------+------+------------+---------------+
-
示例 2:自定义表格样式
from prettytable import PrettyTable table = PrettyTable() table.field_names = ["City name", "Area", "Population", "Annual Rainfall"] table.add_row(["Adelaide", 1295, 1158259, 600.5]) table.add_row(["Darwin", 112, 120900, 1714.7]) table.add_row(["Sydney", 2058, 4336374, 1214.8]) # 自定义样式 table.border = False table.align["City name"] = "l" table.align["Area"] = "r" table.align["Population"] = "c" table.max_width = 10 print(table)
输出:
City name Area Population Annual Rainfall Adelaide 1295 1158259 600.5 Darwin 112 120900 1714.7 Sydney 2058 4336374 1214.8
-
示例 3:假设高铁一节车厢的座位数有6行,每行5列,每个座位初始显示“有票”,)用户输入座位位置(如,4,3)后,按回车,则该座位显示为“已售”
import prettytable as pt
# 显示坐席
def show_ticket(row_num, sold_seats=None):
tb = pt.PrettyTable()
tb.field_names = ['行号', '座位1', '座位2', '座位3', '座位4', '座位5']
for i in range(1, row_num + 1):
lst = [f'第{i}行', '有票', '有票', '有票', '有票', '有票']
if sold_seats:
for seat in sold_seats:
if seat[0] == i:
lst[seat[1]] = '已售'
tb.add_row(lst)
print(tb)
# 订票
def order_ticket(row_num, row, column, sold_seats):
# 检查座位是否已售
if (int(row), int(column)) in sold_seats:
print(f"第{row}排,第{column}列的座位已被售出,请重新选择!")
return False
else:
sold_seats.append((int(row), int(column))) # 添加到已售座位列表
return True
if __name__ == '__main__':
row_num = 6
sold_seats = [] # 用于记录已售座位
show_ticket(row_num, sold_seats) # 显示初始座位信息
# 开始售票
a = True
while a:
choose_num = input('请输入您选择的座位:如4,3表示第四排,第三列:')
row, column = choose_num.split(',')
if order_ticket(row_num, row, column, sold_seats): # 如果订票成功
show_ticket(row_num, sold_seats) # 显示更新后的座位信息
b = input("还需要继续购票吗y|n:")
if b == 'y':
a = True
else:
a = False
print("您购买的座位有:")
for seat in sold_seats:
print(f"第{seat[0]}排,第{seat[1]}列")
print("祝您旅途愉快!")
十二、wordcloud模块
1. 简介
- 定义:
wordcloud
是一个用于生成词云的 Python 库,它可以将文本数据中的单词以可视化的方式展示出来,单词的大小和颜色通常与其出现的频率成正比。 - 特点:
- 支持多种字体和颜色方案,可以自定义词云的形状、颜色和字体。
- 可以从文本文件、字符串或词频字典生成词云。
- 支持中文显示,但需要指定支持中文的字体。
- 生成的词云可以保存为图片文件,方便在报告或网页中展示。
- 应用场景:
- 文本分析:快速了解文本数据中的关键词汇。
- 数据可视化:将文本数据以直观的方式呈现,增强可读性。
- 社交媒体分析:分析用户评论、帖子中的热点词汇。
2. 安装
-
安装方法:
-
使用 pip 命令安装:
pip install wordcloud
-
3. 常用功能
-
生成词云:
-
从文本字符串生成词云:
from wordcloud import WordCloud import matplotlib.pyplot as plt text = "Python is a great programming language for data analysis and visualization" wordcloud = WordCloud().generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show() ------------- generate(text) 方法将文本内容转换为词云图像
-
从文本文件生成词云:
with open('example.txt', 'r', encoding='utf-8') as file: text = file.read() wordcloud = WordCloud().generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
-
-
自定义词云样式:
-
设置字体:
wordcloud = WordCloud(font_path='path/to/your/font.ttf').generate(text)
-
设置词云形状:
from wordcloud import WordCloud import numpy as np from PIL import Image mask = np.zeros((300, 300), dtype=np.uint8) # 创建一个形状模板 mask[100:200, 100:200] = 255 # 在模板中定义一个正方形区域 wordcloud = WordCloud(mask=mask).generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
-
设置颜色方案:
wordcloud = WordCloud(colormap='viridis').generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
-
-
生成词云并保存为图片:
wordcloud.to_file('wordcloud.png')
-
处理中文文本:
-
中文文本需要指定支持中文的字体,否则可能出现乱码:
wordcloud = WordCloud(font_path='path/to/simhei.ttf').generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
-
-
从词频字典生成词云:
word_freq = {'Python': 10, 'Data': 8, 'Analysis': 6, 'Visualization': 4} wordcloud = WordCloud().generate_from_frequencies(word_freq) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
4. 示例
-
示例 1:生成简单的词云
from wordcloud import WordCloud import matplotlib.pyplot as plt text = "Python is a great programming language for data analysis and visualization" wordcloud = WordCloud().generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
-
示例 2:生成中文词云
from wordcloud import WordCloud import matplotlib.pyplot as plt text = "Python 是一种非常适合数据分析和可视化的编程语言" wordcloud = WordCloud(font_path='path/to/simhei.ttf').generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
-
示例 3:生成自定义形状的词云
from wordcloud import WordCloud import numpy as np from PIL import Image import matplotlib.pyplot as plt mask = np.zeros((300, 300), dtype=np.uint8) mask[100:200, 100:200] = 255 wordcloud = WordCloud(mask=mask).generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") plt.show()
5. 应用
-
词云图
需求:使用Python第三方库jieba与wordcloud实现对一个人评论的词云图
import jieba from wordcloud import WordCloud # 读取数据 with open('man.txt', 'r', encoding='utf-8') as file: s = file.read() # 中文分词 lst = jieba.lcut(s) # 排除词 stopword = {'他是一个'} txt = ''.join(lst) # 绘制云图 wordcloud = WordCloud(background_color='white',font_path='msyh.ttc',stopwords=stopword,width=800,height=600) # 有txt生成词云图 wordcloud.generate(txt) # 保存图片 wordcloud.to_file('man.png')