前置动作:系统中文字体安装

  1. 安装文泉雅正:
1
sudo apt-get install fonts-wqy-zenhei
  1. 更新系统字体cache
1
fc-cache -fv

后续操作:

matplotlib

参考:4步永久解决Python matplotlib库显示中文字体乱码问题
实操中第二步不用必须做,因为matplotlib可以从系统字体中自己加载字体,所以只要前面安装系统字体的环节做好了就可以,这样字体管理上也会比较清晰。
重点是第三步:

text
1
2
3
4
5
6
7
8
# 配置文件是步骤1获取的文件路径下matplotlibrc文件
# 修改以下三处:
# (1) 去除行首#,并新增你上传的字体名,如
font.family: WenQuanYi Zen Hei, sans-serif
# (2) 去除行首#,并新增你上传的字体名,后面原始的无需修改,如
font.serif: WenQuanYi Zen Hei, ......
# (3) 去除行首#,将True改为False,如
axes.unicode_minus: False

然后删除 Matplotlib 的字体缓存文件

1
rm -rf ~/.cache/matplotlib

检查 Matplotlib 是否能正确加载新字体

1
2
3
import matplotlib.font_manager as fm
a = sorted([f.name for f in fm.fontManager.ttflist])
print(a)

若需要在代码中临时处理:

1
2
plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei']
plt.rcParams['axes.unicode_minus'] = False

wordcloud

参考:词云库wordcloud中文乱码解决办法
实践时不知道是不是下载错了不好的simhei.ttf,绘制时报错(类似错误的format这类),所以也换成了文泉雅正,并采用了不必改动包的办法(防止更新后失效等)
查询系统字体路径:

1
fc-list

字体太多的话可以筛选特定语言支持

1
fc-list :lang=zh

复制路径到~/.bashrc文件底部:

1
export FONT_PATH='/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc'

保存后重启终端或重新加载.bashrc

1
source ~/.bashrc

经测试很管用。

若需要在代码中临时处理:

1
2
font = '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc
wordcloud = WordCloud(scale=4, font_path=font, background_color="white", width=1000, height=860, margin=2).generate(word)