You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyvis可视化简单图触发UnicodeEncodeError的原因及UTF-8设置方法

解决Pyvis可视化时的UnicodeEncodeError错误

这个错误源于Windows系统中Python默认使用cp1252编码写入文件,而pyvis生成的HTML包含该编码无法处理的Unicode字符,导致写入失败。以下是两种可行的解决方式:

方法1:直接调用write_html指定UTF-8编码

替换原代码中的net.show()方法,直接使用write_html并显式指定编码参数:

net = Network(notebook=True, cdn_resources='in_line')
net.from_nx(nx.davis_southern_women_graph())
# 指定utf-8编码写入HTML,open_browser=True会自动打开页面
net.write_html('example.html', encoding='utf-8', open_browser=True)

方法2:手动写入HTML内容

如果需要更灵活的控制,可以手动获取HTML内容后用UTF-8编码写入文件:

net = Network(notebook=True, cdn_resources='in_line')
net.from_nx(nx.davis_southern_women_graph())
# 获取pyvis生成的HTML字符串
html_content = net.html
# 以UTF-8编码写入文件
with open('example.html', 'w', encoding='utf-8') as f:
    f.write(html_content)

# 可选:手动打开生成的HTML文件
import webbrowser
webbrowser.open('example.html')

两种方法的核心都是强制使用UTF-8编码写入文件,覆盖系统默认的cp1252编码,从而支持所有Unicode字符,解决编码错误问题。

内容的提问来源于stack exchange,提问作者Travelling Salesman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:07:32