【实战】Streamlit搭建Python章节代码可视化系统
·
【实战】Streamlit搭建Python章节代码可视化系统
在日常学习和教学中,我们经常会遇到多章节代码文件管理的问题,手动切换文件夹、打开文件查看代码效率极低。本文将手把手教你用Streamlit快速搭建一个Python章节代码可视化系统,支持左侧章节导航、文件选择、代码高亮展示,还能搜索代码内容,完美适配多章节代码管理场景。
一、效果预览
1. 界面布局
- 左侧侧边栏:章节导航+文件列表,支持8个章节的快速切换
- 右侧主区域:代码内容展示+文件信息+内容搜索,宽布局适配代码阅读
- 支持
.py/.txt/.md文件,Python代码自动高亮,中文编码兼容
2. 核心功能
✅ 按章节分类管理代码文件
✅ 代码高亮展示,支持中文编码(UTF-8/GBK)
✅ 代码内容关键词搜索+高亮
✅ 显示文件大小等基础信息
✅ 适配任意多章节的文件夹结构
二、完整代码
import streamlit as st
import os
import re
# -------------------------- 配置项(适配真实文件夹名称) --------------------------
# 根目录(自动获取当前脚本所在目录)
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# 章节名称(完全匹配你的实际文件夹名)
CHAPTERS = [
"第1章 Python基础知识",
"第2章 Numpy",
"第3章 Pandas",
"第4章 Matplotlib",
"第5章 数据预处理与特征工程",
"第6章 机器学习与实现",
"第7章 集成学习与实现",
"第8章 深度学习与实现"
]
# 支持展示的代码文件后缀
SUPPORTED_EXTENSIONS = (".py", ".txt", ".md")
# -------------------------- 工具函数 --------------------------
def get_chapter_files(chapter_name):
"""获取指定章节文件夹下的所有支持的文件"""
chapter_dir = os.path.join(ROOT_DIR, chapter_name)
if not os.path.exists(chapter_dir):
return []
# 遍历文件夹,筛选支持的文件
file_list = []
for file in os.listdir(chapter_dir):
# 排除隐藏文件,只保留指定后缀
if not file.startswith(".") and file.endswith(SUPPORTED_EXTENSIONS):
file_list.append(file)
return sorted(file_list)
def read_file_content(chapter_name, file_name):
"""读取指定文件的内容,处理编码问题"""
file_path = os.path.join(ROOT_DIR, chapter_name, file_name)
try:
# 优先用utf-8编码读取,失败则用gbk(兼容中文)
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
except UnicodeDecodeError:
with open(file_path, "r", encoding="gbk") as f:
content = f.read()
return content
def highlight_code(content, lang="python"):
"""代码高亮展示(Streamlit原生支持)"""
st.code(content, language=lang)
# -------------------------- 页面布局 --------------------------
def main():
# 页面基础配置
st.set_page_config(
page_title="Python代码章节可视化系统",
page_icon="📚",
layout="wide" # 宽布局,适配代码展示
)
# 侧边栏 - 章节选择
st.sidebar.title("章节导航")
selected_chapter = st.sidebar.selectbox(
"选择章节",
CHAPTERS,
index=0 # 默认选中第1章
)
# 侧边栏 - 文件选择(根据选中章节加载)
st.sidebar.subheader("文件列表")
chapter_files = get_chapter_files(selected_chapter)
if not chapter_files:
st.sidebar.warning(f"「{selected_chapter}」文件夹下暂无支持的文件")
selected_file = None
else:
selected_file = st.sidebar.selectbox(
"选择文件",
chapter_files
)
# 主内容区 - 展示内容
st.title(f"📖 {selected_chapter} 代码查看")
st.divider()
if selected_file:
# 展示文件信息
col1, col2 = st.columns([8, 2])
with col1:
st.subheader(f"文件:{selected_file}")
with col2:
file_path = os.path.join(ROOT_DIR, selected_chapter, selected_file)
file_size = os.path.getsize(file_path) / 1024 # 转换为KB
st.caption(f"文件大小:{file_size:.2f} KB")
# 读取并展示文件内容
content = read_file_content(selected_chapter, selected_file)
# 判断文件类型,针对性展示
if selected_file.endswith(".py"):
highlight_code(content, lang="python")
elif selected_file.endswith(".md"):
st.markdown(content)
else:
st.text(content)
# 可选:添加内容搜索框
st.divider()
search_key = st.text_input("🔍 搜索文件内容")
if search_key:
# 高亮匹配的关键词
pattern = re.compile(re.escape(search_key), re.IGNORECASE)
highlighted_content = pattern.sub(f"**{search_key}**", content)
if selected_file.endswith(".py"):
st.subheader("搜索结果")
st.code(highlighted_content, language="python")
else:
st.subheader("搜索结果")
st.markdown(highlighted_content)
else:
# 无文件时的提示
st.info("请在左侧侧边栏选择章节,并确保对应章节文件夹内有.py/.txt/.md文件")
st.image("https://streamlit.io/images/brand/streamlit-logo-secondary-colormark-darktext.png", width=400)
if __name__ == "__main__":
main()
三、代码解析
1. 配置项(核心适配点)
# 根目录:自动获取脚本所在目录,无需手动修改
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
# 章节列表:必须完全匹配你的实际文件夹名称
CHAPTERS = [
"第1章 Python基础知识",
"第2章 Numpy",
...
]
# 支持的文件类型:可根据需求扩展(如.ipynb)
SUPPORTED_EXTENSIONS = (".py", ".txt", ".md")
关键说明:CHAPTERS列表要和本地章节文件夹名称完全一致,否则会出现“找不到文件夹”的问题。
2. 工具函数(核心功能封装)
(1)获取章节文件列表
def get_chapter_files(chapter_name):
"""获取指定章节文件夹下的所有支持的文件"""
chapter_dir = os.path.join(ROOT_DIR, chapter_name)
if not os.path.exists(chapter_dir):
return []
file_list = []
for file in os.listdir(chapter_dir):
# 排除隐藏文件,只保留指定后缀
if not file.startswith(".") and file.endswith(SUPPORTED_EXTENSIONS):
file_list.append(file)
return sorted(file_list)
功能:遍历指定章节文件夹,筛选出非隐藏的、指定后缀的文件,返回排序后的文件列表。
(2)读取文件内容(兼容中文编码)
def read_file_content(chapter_name, file_name):
"""读取指定文件的内容,处理编码问题"""
file_path = os.path.join(ROOT_DIR, chapter_name, file_name)
try:
# 优先用utf-8编码读取
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
except UnicodeDecodeError:
# 失败则用gbk(兼容中文文件)
with open(file_path, "r", encoding="gbk") as f:
content = f.read()
return content
核心亮点:解决中文文件读取乱码问题,优先UTF-8,兼容GBK编码。
(3)代码高亮展示
def highlight_code(content, lang="python"):
"""代码高亮展示(Streamlit原生支持)"""
st.code(content, language=lang)
利用Streamlit原生的st.code实现代码高亮,支持Python、Java等多种语言。
3. 页面布局(UI实现)
(1)基础配置
st.set_page_config(
page_title="Python代码章节可视化系统",
page_icon="📚",
layout="wide" # 宽布局,适配代码阅读
)
设置页面标题、图标和宽布局,提升代码展示体验。
(2)侧边栏:章节+文件选择
# 章节选择
st.sidebar.title("章节导航")
selected_chapter = st.sidebar.selectbox("选择章节", CHAPTERS, index=0)
# 文件选择(根据选中章节动态加载)
st.sidebar.subheader("文件列表")
chapter_files = get_chapter_files(selected_chapter)
if not chapter_files:
st.sidebar.warning(f"「{selected_chapter}」文件夹下暂无支持的文件")
selected_file = None
else:
selected_file = st.sidebar.selectbox("选择文件", chapter_files)
侧边栏分为两部分:章节下拉选择、文件下拉选择(根据章节动态加载),无文件时给出友好提示。
(3)主内容区:文件展示+搜索
if selected_file:
# 展示文件名称和大小
col1, col2 = st.columns([8, 2])
with col1:
st.subheader(f"文件:{selected_file}")
with col2:
file_path = os.path.join(ROOT_DIR, selected_chapter, selected_file)
file_size = os.path.getsize(file_path) / 1024
st.caption(f"文件大小:{file_size:.2f} KB")
# 读取并展示文件内容(按类型适配)
content = read_file_content(selected_chapter, selected_file)
if selected_file.endswith(".py"):
highlight_code(content, lang="python")
elif selected_file.endswith(".md"):
st.markdown(content)
else:
st.text(content)
# 代码内容搜索
search_key = st.text_input("🔍 搜索文件内容")
if search_key:
pattern = re.compile(re.escape(search_key), re.IGNORECASE)
highlighted_content = pattern.sub(f"**{search_key}**", content)
if selected_file.endswith(".py"):
st.subheader("搜索结果")
st.code(highlighted_content, language="python")
else:
st.markdown(highlighted_content)
- 展示文件基础信息(名称、大小);
- 按文件类型适配展示方式(Python代码高亮、Markdown解析、文本直接展示);
- 关键词搜索:忽略大小写,匹配内容高亮显示。
四、环境准备与运行
1. 安装依赖
pip install streamlit
2. 文件夹结构要求
根目录/
├── 第1章 Python基础知识/
│ └── demo1.py # 章节内的代码文件
├── 第2章 Numpy/
│ └── numpy_demo.py
├── ...
└── app.py # 上述代码文件
关键:代码文件要放在对应章节文件夹内,根目录只放主脚本app.py。
3. 启动系统
streamlit run app.py
启动后会自动打开浏览器,地址默认为 http://localhost:8501。
五、扩展优化(可选)
- 支持Jupyter笔记本(.ipynb):安装
nbconvert库,解析.ipynb文件内容; - 代码运行功能:结合
exec/subprocess实现代码一键运行(注意安全风险); - 代码行号显示:使用
pygments库生成带行号的高亮代码; - 暗黑模式适配:Streamlit默认支持,可在页面设置中切换;
- 文件上传功能:支持在线上传代码文件到指定章节。
六、总结
本文实现的Streamlit代码可视化系统,核心解决了“多章节代码文件管理+可视化查看”的痛点,代码结构清晰、易扩展,适合Python学习者、教师、开发者使用。只需修改CHAPTERS列表适配自己的文件夹结构,即可快速搭建专属的代码管理系统。
Python代码章节可视化系统
更多推荐


所有评论(0)