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

VS Code中Python输出与Matplotlib法语编码冲突问题求助

解决VS Code中Python编码与Matplotlib文本显示冲突问题

核心问题根源

你的问题是VS Code终端编码、Python源文件编码、Matplotlib字体编码三者不匹配导致的矛盾:

  • 用# -*- coding: utf-8 -*-时,源文件是UTF-8,但终端默认编码不是UTF-8,所以print输出乱码;Matplotlib默认读取UTF-8文本,所以显示正常。
  • 用# -*- coding: Latin-1 -*-时,源文件是Latin-1,终端编码匹配所以print正常,但Matplotlib以UTF-8解析文本,导致乱码。

分步解决方案

1. 统一源文件编码为UTF-8

  • 代码开头固定添加:# -*- coding: utf-8 -*-
  • 确认VS Code右下角的文件编码为UTF-8,若不是,点击编码选择「通过编码保存」→ 选UTF-8。

2. 修复终端print乱码

强制Python标准输出使用UTF-8编码,在代码开头添加:

import sys
sys.stdout.reconfigure(encoding='utf-8')

或者直接在VS Code设置中配置终端编码:

  • 打开设置(快捷键Ctrl+,)
  • 搜索terminal.integrated.encoding,将值设为utf-8

3. 确保Matplotlib文本显示正常

给Matplotlib指定支持拉丁字符的UTF-8字体,在导入Matplotlib后添加:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['DejaVu Sans']  # 该字体默认支持拉丁字符,跨平台可用
plt.rcParams['axes.unicode_minus'] = False

如果是Windows系统,也可以替换为系统自带的'Segoe UI'等支持UTF-8的字体。

测试验证

按上述配置后,执行以下代码即可同时正常显示print输出和Matplotlib文本:

# -*- coding: utf-8 -*-
import sys
sys.stdout.reconfigure(encoding='utf-8')
import matplotlib.pyplot as plt

print('à')

plt.text(0.5, 0.5, 'à', fontsize=20)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:59:56