本文是在“基于Python的词云生成(一)”的基础上进行的进一步扩展,重点介绍了如何利用jieba分词包对中文文本进行分词处理,以生成更加美观且具有分析价值的词云。jieba分词包是一个强大的Python库,专门针对中文进行了优化,能够高效地处理各种复杂的中文文本。
jieba分词包支持三种分词模式: - 精准模式:力求将句子精确地切分为词语,适合文本分析; - 全模式:将句子中的所有可能的词语都提取出来,速度快但无法解决歧义问题; - 搜索引擎模式:在精准模式基础上,对长词进行二次切割,提高召回率,适用于搜索引擎分词。
此外,jieba分词包还支持自定义词典功能,可以方便地添加特定词汇,以便更好地处理特定领域的文本。
```python import jieba from os import path from PIL import Image import numpy as np import matplotlib.pyplot as plt from wordcloud import WordCloud, ImageColorGenerator import matplotlib.font_manager as fm
d = path.dirname(file)
bg = np.array(Image.open("man.jpg"))
stopwordspath = 'stopwords.txt' with open(stopwordspath, encoding="utf8") as fstop: fstoptext = fstop.read() f_stop.close()
def jiebaclearText(text): mywordList = [] seglist = jieba.cut(text, cutall=False) listStr = '/'.join(seg_list)
f_stop_seg_list = f_stop_text.split("n")
for myword in listStr.split('/'):
if not (myword.split()) in f_stop_seg_list and len(myword.strip()) > 1:
mywordList.append(myword)
return ' '.join(mywordList)
textpath = "人民的名义.txt" text = open(path.join(d, textpath), encoding="utf8").read()
text1 = jiebaclearText(text)
wc = WordCloud( backgroundcolor="white", maxwords=200, mask=bg, maxfontsize=60, randomstate=42, fontpath='C:/Windows/Fonts/simkai.ttf' ).generate(text1)
my_font = fm.FontProperties(fname='C:/Windows/Fonts/simkai.ttf')
image_colors = ImageColorGenerator(bg)
plt.imshow(wc.recolor(colorfunc=imagecolors)) plt.axis("off") plt.figure() plt.imshow(bg, cmap=plt.cm.gray) plt.axis("off")
wc.to_file("man.png") ```
保存后的图片如下:
如需获取更多相关资料,请关注我的订阅号(ID:pipizongITR),并在对话框中输入“wordcloudch”。
希望本文对你有所帮助,如果有任何错误或建议,欢迎指正。