import jieba
from wordcloud import WordCloud
txt = '弱小的人,才习惯,嘲讽和否定,而内心,强大的人,从不吝啬赞美和鼓励'
words = jieba.lcut(txt)
newtxt = " ".join(words)
print(newtxt)
font = r"C:\Windows\Fonts\simhei.ttf"
wordcloud = WordCloud(font_path=font).generate(newtxt)
wordcloud.to_file("词云图.jpg")
以上是代码片段,无法正常生成词云图片
以上图片是报错信息
你把报错发给我看一下
new_data = re.findall(’[\u4e00-\u9fa5]+’, data, re.S)
new_data = " ".join(new_data)
对于中文词云制作,可以使用Python中的wordcloud库来实现。具体步骤如下:
1.安装wordcloud库,可以使用pip命令进行安装:
pip install wordcloud
2.导入需要的库:
import jieba # 中文分词库
from wordcloud import WordCloud
import matplotlib.pyplot as plt
3.读取文本数据,使用jieba库对文本进行中文分词:
text = "中文文本"
cut_text = jieba.cut(text) # 对文本进行中文分词
4.将分词结果拼接成一个字符串:
result = " ".join(cut_text) # 将分词结果拼接成一个字符串
5.创建WordCloud对象,并使用fit_words()方法将分词结果传入:
wc = WordCloud(
font_path="simsun.ttf", # 指定中文字体
width=800, height=600 # 图片大小
)
wc.fit_words(result) # 将分词结果传入
6.使用matplotlib展示生成的词云图:
plt.imshow(wc) # 使用imshow()方法展示词云图
plt.axis("off") # 隐藏坐标轴
plt.show() # 显示图片
需要注意的是,在安装中文字体时,需要注意操作系统的区别,如果是Windows系统可以使用“微软雅黑”、“SimHei”等常用中文字体;如果是Ubuntu系统可以使用“SimSun”、“SimHei”等字体。
另外,如果出现“font not found”错误,可以使用以下方法解决:
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 指定中文字体
matplotlib.rcParams['font.family'] = 'sans-serif'
以上是一些基本的步骤和方法,根据实际需要还可以对词云的颜色、形状等进行更加详细的设置。如果还有其他问题,可以参考wordcloud库官方文档:https://amueller.github.io/word_cloud/index.html。