如何在Python中生成带语法高亮的代码可视化图像?
方案1:用Pygments直接生成高亮代码图像(最简便)
Pygments是Python原生的语法高亮工具,自带图像格式化器,能直接把代码转成带高亮的图片,完全不需要依赖LaTeX,步骤简单:
- 先安装依赖:
pip install pygments - 示例代码:
from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import ImageFormatter # 要高亮的代码片段 code = """ def hello_world(): print("Hello, highlighted code!") for i in range(5): print(i) """ # 生成高亮图像,可自定义字体、行号、样式 highlighted_image = highlight(code, PythonLexer(), ImageFormatter( font_name='Consolas', font_size=14, line_numbers=True, line_number_bg='#f0f0f0', line_number_fg='#666666' )) # 保存图像 with open('highlighted_code.png', 'wb') as f: f.write(highlighted_image)
如果只是需要把代码转成带高亮的独立图像,这是最省事的选择。
方案2:将Pygments生成的SVG嵌入Matplotlib
如果需要把高亮代码整合到Matplotlib图表里(比如作为注释或子图),可以用Pygments生成SVG格式的高亮代码,再导入到Matplotlib中:
import matplotlib.pyplot as plt from matplotlib.offsetbox import OffsetImage, AnnotationBbox from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import SvgFormatter import io # 代码片段 code = """ def plot_data(x, y): plt.figure(figsize=(10,6)) plt.plot(x, y, color='blue', linewidth=2) plt.title('Sample Plot') plt.show() """ # 生成SVG格式的高亮代码,支持多种内置样式 svg_code = highlight(code, PythonLexer(), SvgFormatter( font_name='Consolas', font_size=12, style='monokai' # 可选样式:solarized-dark, github等 )) # 将SVG转为Matplotlib可读取的对象 svg_file = io.BytesIO(svg_code.encode('utf-8')) img = plt.imread(svg_file, format='svg') # 创建Matplotlib图表并嵌入高亮代码 fig, ax = plt.subplots(figsize=(8, 5)) ax.plot([1,2,3,4], [1,4,9,16]) # 示例图表 # 把高亮代码作为注释添加到图表中 imagebox = OffsetImage(img, zoom=0.8) ab = AnnotationBbox(imagebox, (2.5, 10), frameon=True, pad=0.5) ax.add_artist(ab) plt.tight_layout() plt.savefig('plot_with_code.png') plt.show()
这个方法能无缝把高亮代码和Matplotlib图表结合,样式可控,不需要复杂的环境配置。
方案3:Matplotlib内部直接渲染高亮代码
如果不想依赖外部文件,完全在Matplotlib里实现语法高亮,可以用Pygments解析代码的语法Token,再逐个设置文本颜色:
import matplotlib.pyplot as plt from pygments import lex from pygments.lexers import PythonLexer # 代码片段 code = """ def calculate_sum(numbers): total = 0 for num in numbers: total += num return total result = calculate_sum([1,2,3,4,5]) print(result) """ # 用Pygments解析代码为语法Token列表 tokens = list(lex(code, PythonLexer())) # 自定义Token对应的颜色(可根据需求调整) token_colors = { 'Keyword': '#ff0000', # 关键字(def, return等) 'Name.Function': '#0000ff', # 函数名 'String': '#008000', # 字符串 'Comment': '#808080', # 注释 'Number': '#800080', # 数字 'Operator': '#000000', # 操作符 'Text': '#000000' # 普通文本 } # 创建Matplotlib画布,隐藏坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) ax.axis('off') # 逐行渲染代码 y_pos = 0.9 # 起始y坐标 line_height = 0.08 # 行间距 current_line = [] current_x = 0.1 # 每行起始x坐标 for token_type, token_text in tokens: lines = token_text.split('\n') for i, line in enumerate(lines): if i > 0: # 渲染当前收集的行 if current_line: x_offset = current_x for text, color in current_line: ax.text(x_offset, y_pos, text, fontfamily='monospace', fontsize=12, color=color, va='top') x_offset += len(text) * 0.015 # 调整字符间距 current_line = [] y_pos -= line_height current_x = 0.1 if line: # 获取当前Token的颜色 color = token_colors.get(token_type.split('.')[0], '#000000') current_line.append((line, color)) # 渲染最后一行 if current_line: x_offset = current_x for text, color in current_line: ax.text(x_offset, y_pos, text, fontfamily='monospace', fontsize=12, color=color, va='top') x_offset += len(text) * 0.015 plt.tight_layout() plt.savefig('matplotlib_code_highlight.png') plt.show()
这个方案完全在Matplotlib内部实现,适合需要高度自定义代码显示位置、样式的场景。
关于LaTeX+minted方案失效的说明
Matplotlib的LaTeX渲染依赖系统完整的LaTeX环境,不仅要启用text.usetex=True,还要确保系统安装了minted包和pygmentize工具,配置步骤繁琐且容易受环境差异影响,所以上述Pygments方案更可靠简便。
内容的提问来源于stack exchange,提问作者Luca Cappelletti
相关产品推荐
相关产品推荐

