非Jupyter环境下PyAgrum CPT可视化的PDF保存与HTML获取问询
PyAgrum showCPTs 可视化保存PDF与获取HTML方案
获取showCPTs对应的HTML内容
在.py文件中,可以直接使用pyAgrum.lib.notebook.getHTML()函数获取showCPTs()生成的HTML内容——因为showCPTs()本质上就是调用该函数生成HTML后在Jupyter中渲染展示的。
代码示例
import pyAgrum as gum import pyAgrum.lib.notebook as gnb # 示例:构建简单贝叶斯网络 bn = gum.BayesNet("Example") A = bn.add(gum.LabelizedVariable("A", "A", ["a1", "a2"])) B = bn.add(gum.LabelizedVariable("B", "B", ["b1", "b2"])) bn.addArc(A, B) bn.cpt(A).fillWith([0.6, 0.4]) bn.cpt(B)[A[0]] = [0.7, 0.3] bn.cpt(B)[A[1]] = [0.2, 0.8] # 获取单个节点CPT的HTML single_cpt_html = gnb.getHTML(bn.cpt("A")) # 获取所有节点CPTs的HTML(与showCPTs()展示内容一致) all_cpts_html = gnb.getHTML(bn)
将CPTs可视化保存为PDF
showCPTs()没有直接导出PDF的方法,但可以先获取上述HTML内容,再借助HTML转PDF的工具库实现。
方法1:使用WeasyPrint
WeasyPrint是纯Python的HTML/CSS转PDF库,无需额外依赖外部工具:
from weasyprint import HTML # 将所有CPTs的HTML保存为PDF HTML(string=all_cpts_html).write_pdf("bayesian_network_cpts.pdf")
安装依赖:pip install weasyprint
方法2:使用pdfkit
pdfkit依赖wkhtmltopdf工具,跨平台支持较好:
import pdfkit # 将HTML保存为PDF pdfkit.from_string(all_cpts_html, "bayesian_network_cpts.pdf")
- 安装依赖:
pip install pdfkit - 额外安装wkhtmltopdf:
- Ubuntu/Debian:
sudo apt-get install wkhtmltopdf - Windows/macOS:下载对应系统的安装包并配置环境变量
- Ubuntu/Debian:
内容的提问来源于stack exchange,提问作者Bennett Jackson
相关产品推荐
相关产品推荐

