文本挖掘是將文本信息轉化為可利用的數據的知識。
一、創建“語料庫”
語料庫(Corpus)是我們要分析的所有文檔的集合。
將現有的文本文檔的內容添加到一個新的語料庫中。
實現邏輯:
將各文本文件分類放置在一個根目錄下,通過遍歷讀取根目錄下所有子目錄中的所有文件,
然后將讀取結果賦值到一個數據框中,得到含有文件路徑、文件內容的結果。
代碼核心:
構建方法:os.walk(fileDir) 對在fileDir目錄下的所有文件(for循環)進行操作 ,得到文件路徑
文件讀取:codecs.open(filepath,medthod,encoding) 文件路徑、打開方式(r,w,rw)、文件編碼 ,得到文本內容
#構建語料庫 import codecs filepaths = [] #構建一個空的‘文件路徑’列表 filecontents = [] #構建一個空的‘文件內容’列表 for root, dirs, files in os.walk('.\SogouC.mini\Sample'): for name in files: #拼接文件路徑,得到所有子文件夾下的文件的文件路徑的列表 filepaths,包含根目錄、子目錄和文件名 filepath = os.path.join(root,name) filepaths.append(filepath) #將所有子文件夾下的文件路徑的列表合並到一個新的列表中 #打開文件,‘r’表示只讀,編碼方式‘utf-8’ f = codecs.open(filepath,'r','utf-8') filecontent = f.read() #讀取文件,並將內容傳入到 'filecontent'(文件內容)列表中 f.close() #關閉文件 filecontents.append(filecontent) #將所有子文件夾下的文件內容的列表合並到一個新的列表中 import pandas as pd #根據得到的合並后的文件路徑和文件內容,得到語料庫的數據框 corpos = pd.DataFrame({ 'filePath':filepaths, 'fileContent':filecontents}) corpos.to_csv('.\corpos.csv',sep=',',encoding='utf_8_sig',index=False)
###防止保存時出現亂碼,需要參數encoding='utf_8_sig'
二、中文分詞
一般使用 jieba 中文分詞包,較友好(簡單,方便,准確率高)
jieba包的部分用法:
- jieba.cut('str') 對str進行分詞
- jieba.add_word() 增加自定義分詞
- jieba.load_userdict() 通過導入本地文件中的詞,將之添加到詞庫
分詞實現代碼:
import jieba #創建詞組和路徑的空列表 segments = [] filepath_2 = [] #對語料庫的每行遍歷( for index, row in corpos.iterrows(): filePath = row['filePath'] #文件路徑 fileContent = row['fileContent'] #文本內容 segs = jieba.cut(fileContent) #對文本內容分詞 #對分詞結果遍歷,將每個詞及其路徑分別添加到segments和filepath_2列表中 for seg in segs: segments.append(seg) filepath_2.append(filePath) #將兩個列表合並到數據框中(詞,路徑) segmeng_DF = pd.DataFrame({ 'segment': segments, 'filePath': filepath_2})
最終得到各個詞及其路徑的數據框
三、詞頻統計
得到含有分詞結果的數據后,需要對分詞出現的次數進行統計,得到詞頻表
#####詞頻統計 import numpy as np #根據前面的分詞結果,對每個詞的詞頻進行統計,再根據詞頻大小排序 segcount = segmeng_DF.groupby(by='segment')['segment'].agg({ '頻數':np.size }).reset_index().sort_index(by=['頻數'],ascending=False) help(pd.DataFrame.sort_index)
DataFrame不支持sort方法,已更新為sort_index方法
詞頻統計后需要將部分停用詞(語氣詞等等無實際意義的詞)進行剔除
!!!這里使用導入的方式確定停用詞,read_csv對中文路徑十分不友好,盡量使用英文路徑
stopwords = pd.read_csv(r'D:\python_study\StopwordsCN.txt',encoding='utf-8',index_col=False)
stopwords即為分詞過程中需要剔除的詞
剔除停用詞的兩種思路:
- 剔除統計詞頻后的分詞結果中含有的停用詞,使用isin方法,“~”取反
- 在構建語料庫的時候添加過濾條件
第一種實現方法:
fsegcount = segcount[~segcount.segment.isin(stopwords.stopword)]
第二種實現方法:
#####在讀取文件時過濾停用詞 import jieba #創建詞組和路徑的空列表 segments = [] filepath_2 = [] #對語料庫的每行遍歷( for index, row in corpos.iterrows(): filePath = row['filePath'] #文件路徑 fileContent = row['fileContent'] #文本內容 segs = jieba.cut(fileContent) #對文本內容分詞 #對分詞結果遍歷,將每個詞及其路徑分別添加到segments和filepath_2列表中 for seg in segs: if (seg not in stopwords.stopword.values) and (len(seg.strip())>0): segments.append(seg) filepath_2.append(filePath) #將兩個列表合並到數據框中(詞,路徑) segmeng_DF = pd.DataFrame({ 'segment': segments, 'filePath': filepath_2}) segcount_1 = segmeng_DF.groupby(by='segment')['segment'].agg({ '頻數':np.size }).reset_index().sort_index(by=['頻數'],ascending=False)
嵌套if函數,通過判斷分詞結果是否在stopwords的值中,剔除停用詞,得到最終的詞頻統計表
四、繪制詞雲
首先需要下載wordcloud程序包,通過whl文件進行庫的安裝
https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud
在cmd中定位下載目錄,輸入 pip install wordcloud-1.5.0-cp36-cp36m-win_amd64.whl 進行安裝
from wordcloud import WordCloud import matplotlib.pyplot as plt #傳入字體文件的路徑及背景顏色兩個參數 wordcloud = WordCloud(font_path=r'D:\python_study\python數據挖掘\數據挖掘學習代碼\課件\2.4\simhei.ttf', background_color='gray')
#wordcloud方法需要傳入字典結構的參數,所以將詞頻結果(數據框)轉換為字典類型
#先將分詞設置為數據框的索引,再使用to_dict方法轉換為字典
words = segcount_1.set_index('segment').to_dict()
type(segcount_1.set_index('segment'))#只有一列的數據框 wordcloud.fit_words(words['頻數'])#根據頻數進行作圖 plt.imshow(wordcloud) plt.close()
最終得到類似與右圖的結果
五、詞雲美化
將詞雲的背景替換成與主題相關的圖片
需要用到的包:
from scipy.misc import imread
from wordcloud import WordCloud, ImageColorGenerator
部分關鍵方法
讀取圖片背景: bimg = imread(imgFilePath)
獲取圖片顏色: bimgColors = ImageColorGenerator(bimg)
重置詞雲的顏色: wordcloud.recolor(color_func=bimgColors
#詞雲美化 from scipy.misc import imread from wordcloud import WordCloud, ImageColorGenerator #讀取需要替換的圖片背景: bimg = imread(r'D:\python_study\python數據挖掘\數據挖掘學習代碼\課件\2.5\賈寶玉2.png') #使用了賈寶玉的上半身作為詞雲(別問,懶,隨手拿的) wordcloud = WordCloud( background_color="white", mask=bimg, font_path=r'D:\python_study\python數據挖掘\數據挖掘學習代碼\課件\2.4\simhei.ttf' ) wordcloud = wordcloud.fit_words(words['頻數']) #設置輸出圖形參數 plt.figure( num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') #獲取圖片顏色 bimgColors = ImageColorGenerator(bimg) #移除坐標軸 plt.axis("off") #重置詞雲顏色 plt.imshow(wordcloud.recolor(color_func=bimgColors)) plt.show()
最終得到右圖的結果