上一篇文章講了如何抓取朋友圈文本資訊,這篇文章将如何将其可視化,生成詞雲。生成詞雲需要先分詞,利用python的jieba包分詞,然後根據tf-idf算法提取出關鍵詞。利用python的wordcloud包可以生成詞雲,但是wordcloud包生成詞雲是單純依據詞頻,而沒有使用tf-idf算法。為了改進這點,将分詞後的結果根據tf-idf值建構新的字元串,使得tf-idf值大的詞在新字元串中詞頻也大,再利用wordcloud包生成新字元串的詞雲圖
注釋中講得比較詳細了,直接貼上代碼
#将存儲的文本分詞
def cut_text(store_path):
f=open(store_path,'r',encoding='UTF-8')
text=f.read() #從檔案讀取所有字元并将它們作為字元串傳回
cutted_words=jieba.cut(text)#傳回的是一個生成器
return cutted_words
#剔除停用詞
def store_cut_text(textstore_path,cut_store_path):
cutted_words=cut_text(textstore_path)
#下面把不在停用詞表中的詞語添加到這個字元串中,并用空白符分隔開;
# 必須給個符号分隔開分詞結果形成字元串,否則不能生成詞雲
f=open(cut_store_path,"w",encoding="utf-8")
for w in cutted_words:
f.write(w+"\n")
f.close()
def del_stopwords(stopwords_path,cut_store_path):
stopwords_list = [line.strip() for line in open(stopwords_path, 'r', encoding='utf-8').readlines()] # 将停用詞表轉換成清單
words_str = ''
f=open(cut_store_path,"r",encoding='utf-8')
w=f.readline()
words_dir={}
while w!="":
if w.strip() not in stopwords_list:
if w not in words_dir.keys():
words_dir[w]=1
else:
words_dir[w]+=1
words_str+=w
words_str+=' '
w=f.readline()
set_lst=sorted(words_dir.items(),key= lambda item:item[1],reverse=True) #按字典的值排序,傳回一個二進制元組的清單,元組第一個元素是關鍵字,第二個是值
return words_str
#生成詞雲
def get_wordcloud(words_str,store_path):
background=plt.imread(r'.\res\cloud.jpg') #設定雲圖背景圖案,參數為圖檔路徑,不設定的話雲圖預設為方形
wc=WordCloud(mask=background,font_path=r'.\res\simhei.ttf', #指定字型路徑
background_color='white',width=500,height=350,max_font_size=400,min_font_size=5)
#font_path是中文字型路徑,因為wordcloud庫本身隻支援英文,需要下載下傳中文字型;
# max_font_size和min_font_size分别設定雲圖最大詞語的大小和最小詞語的大小
wc.generate(words_str)#生成詞雲
wc.to_file(store_path)#将詞雲存儲到指定路徑
plt.imshow(wc)#以圖檔形式顯示詞雲
plt.axis('off')#将圖像坐标系關閉
plt.show()
#列印關鍵字
def keywords_delstop(s,n):#提取tf*idf排名前n的n個關鍵詞
tfidf =analyse.extract_tags # 引入TF-IDF關鍵詞抽取接口
keywords=tfidf(s,n,withWeight=True)
print("哈羅皮朋友圈的十大關鍵詞是:")
i=1
while i<11:
print(str(i) + "、" + keywords[i-1][0] )
i+=1
construct_lst=[]#根據tf*idf值建構新的字元串,使得tf*idf值大的詞詞頻也大,以便生成詞雲圖。因為詞雲會單純依據詞頻來生成
for keyword in keywords:
num=round(keyword[1],2)*100 #根據tf-idf值确定詞語在新字元串中的個數
n=0
while n<num:
construct_lst.append(keyword[0])
n+=1
random.shuffle(construct_lst)#将原清單打亂
construct_str=""
for word in construct_lst:
construct_str+=word
construct_str+=" "
return construct_str
if __name__=='__main__':
store_cut_text(r'D:\詞雲\哈羅皮已處理.txt',r'.\temp\哈羅皮切詞.txt') #切詞并存儲切分的詞語
words_str=del_stopwords(r'.\res\stopwords.txt',r'.\temp\哈羅皮切詞.txt') #删除停用詞
construct_str=keywords_delstop(words_str,180) #使用tf-idf值排名前180的詞語構造新字元串
get_wordcloud(construct_str,r'D:\詞雲\哈羅皮.jpg') #用新字元串生成詞雲
最終的效果圖
一年結束的時候可以生成自己這一年的朋友圈詞雲,看看自己這一年的關鍵詞都是哪些,給自己來個年度總結,是不是挺酷的:)
本項目已上傳至github:
https://github.com/moonshine57/Moments_wordCloud