【机器学习】词云(worldcloud)统计词的重要性

 1 from wordcloud import WordCloud,ImageColorGenerator
 2 import matplotlib.pyplot as plt
 3 import jieba
 4 from PIL import Image
 5 import numpy as np
 6 
 7 
 8 # # 1、设置一个文本,显示的文本
 9 # #
10 # with open("./元尊.txt", "r", encoding="utf-8") as f:
11 #     content = f.read()
12 # # print(content)
13 # # 2、对文本进行分词处理---
14 # # 借助jieba 进行精确模式分词
15 # seg = jieba.cut(content, cut_all=False)
16 # content = ",".join(seg)
17 # print("分词之后的结果:\n", content)
18 # # 3、生成一个词云对象
19 # wc = WordCloud(
20 #     # 设置字体
21 #     font_path="./simhei.ttf",
22 #     # 设置背景图的大小
23 #     # mask 参数---可以手动自己指定背景图,一旦设置背景图,那么就不需要设置背景图的宽和高
24 #     width=200,
25 #     height=100,
26 #     # 设置背景颜色
27 #     background_color="white"
28 # )
29 # # 4、借助词云对象来生成词云文本
30 # wc_text = wc.generate(content)
31 # # 5、显示
32 # # 显示样式
33 # # interpolation ---显示方式
34 # plt.imshow(wc_text,interpolation="bilinear")
35 # # 关闭坐标显示
36 # plt.axis("off")
37 # # 显示
38 # plt.show()
39 
40 # 1、生成词云
41 def get_wordcloud():
42     """
43     生成词云
44     :return:
45     """
46     # 1、加载文本
47     with open("./元尊.txt", "r", encoding="utf-8") as f:
48         content = f.read()
49     # print(content)
50     # 2、文本分词
51     # # 借助jieba 进行精确模式分词
52     seg = jieba.cut(content, cut_all=False)
53     content = ",".join(seg)
54     print("分词之后的结果:\n", content)
55     # 3、加载背景图
56     background_image = np.array(Image.open("./1.png"))
57     # 4、生成词云对象
58     wc = WordCloud(
59         # 设置字体
60         font_path="./simhei.ttf",
61         # 设置背景图的大小
62         # mask 参数---可以手动自己指定背景图,一旦设置背景图,那么就不需要设置背景图的宽和高
63         mask=background_image,
64         # 设置背景颜色
65         background_color="white"
66     )
67     # 5、生词词云文本
68     wc_text = wc.generate(content)
69 
70     # 6、提取背景图的颜色,来设置词云文本的颜色
71     color = ImageColorGenerator(background_image)
72 
73     # 7、重新设置 词云文本的颜色
74     wc.recolor(color_func=color)
75 
76 
77     # 8、显示
78     # 显示样式
79     # interpolation ---显示方式
80     plt.imshow(wc_text,interpolation="bilinear")
81     # 关闭坐标显示
82     plt.axis("off")
83     # 显示
84     plt.show()
85 
86 get_wordcloud()

猜你喜欢

转载自www.cnblogs.com/Tree0108/p/12116217.html