一
前幾天在文章《遲到的 2018 年度總結(文內有福利)》中,我使用了分詞和詞雲的展示效果,有不少同學都在後臺問我是怎麼實現的,也希望能用到自己的總結裏面去。
其實主要思路是參考大佬 Python之禪(專業研究 Python,有興趣的同學可以關注) 的文章《北大開源中文分詞工具pkuseg-python,我用張小龍的3萬字演講做了統計》,然後稍微做了下變通。
爲了讓這個工具更易用,我給加了簡單的 UI 界面,這樣所有人都可以無門檻的拿來即用,用完即走了。
而問題就是時間拖的有點晚了,對不起,希望還能對你有所幫助。
二
因爲很多人問,所以我把工具共享出來,需要的同學請後臺回覆「tool」獲取完整源代碼。
下面是圖解使用說明:
下面是關鍵部分的代碼實現:
def on_button_check(self, event):
"""響應 開始統計 按鈕點擊操作"""
content = self._readfiles(self.text_file2.GetValue())
zhuanyong = self._readfiles(self.text_zhuanyong.GetValue())
zhuanyong_list = []
for one in zhuanyong.split('\n'):
zhuanyong_list.append(one)
seg = pkuseg.pkuseg(user_dict=zhuanyong_list)
text = seg.cut(content)
stopwords = self._readfiles(self.text_stop.GetValue())
new_text = []
for word in text:
if word not in stopwords:
new_text.append(word)
counter = Counter(new_text)
print(counter.most_common(20))
word_list = " ".join(new_text)
pic_path = self._cur_file_dir(self.text_pic.GetValue())
coloring = numpy.array(Image.open(pic_path))
wc = WordCloud(background_color="white",
mask=coloring,
font_path="simfang.ttf",
max_font_size=84,
random_state=15,
)
myword = wc.generate(word_list)
#展示詞雲圖
plt.imshow(myword)
plt.axis("off")
plt.show()
以上,希望對你有所幫助,有任何問題歡迎留言和我溝通。