詞頻統(tǒng)計 - 詞云繪制

需求分析:

搜狗實驗室 下載一份迷你版的樣例數(shù)據(jù),解壓后文件名為 ‘SogouC.mini’。作為練習(xí)數(shù)據(jù)對其進行以下幾個實驗:詞頻統(tǒng)計-詞云繪制-關(guān)鍵詞提取-相似文章推薦-自動摘要等實驗。本篇為詞頻統(tǒng)計和詞云繪制篇,后面幾個實驗我會慢慢補上?!甋ogouC.mini’的文件目錄結(jié)構(gòu)如下:

*

開發(fā)環(huán)境:

系統(tǒng): macOS Sierra; 開發(fā)軟件: PyChram CE; 運行環(huán)境: Python3.6


  • 首先導(dǎo)入需要用到的包

import jieba
import pandas
from wordcloud import WordCloud
import matplotlib.pyplot as plt
  • 創(chuàng)建語料庫

filePaths = []
fileContents = []

for root, dirs, files in os.walk(  # 遍歷文件目錄,包括目錄下的子文件
    'data/SogouC.mini/Sample'
):
    for name in files:
        filePath = os.path.join(root, name)  # 組成每個子文件的全路徑
        filePaths.append(filePath)
        f = codecs.open(filePath, 'r', 'utf-8')  #open只能寫入str類型的數(shù)據(jù),某些情況可能會出現(xiàn)編碼錯誤,而codecs.open能避免這個問題
        fileContent = f.read()
        f.close()
        fileContents.append(fileContent)

corpus = pandas.DataFrame({
    'filePath': filePaths,
    'fileContent': fileContents
})
corpus.to_csv('data/corpus.csv', index=False) #將語料庫corpus保存為csv文件

運行結(jié)果如下:(用head()函數(shù)顯示前面5行)


*
  • 讀取停用詞文件

# 讀取停用詞文件(StopwordsCN.txt)
stopWords = pandas.read_csv(
    'data/StopwordsCN.txt',
    encoding='utf-8',
    index_col=False
)
  • 對語料庫進行分詞 & 進行停用詞過濾

# 分詞處理 & 過濾停用詞
for index, row in corpus.iterrows():  # 迭代(iterate)覆蓋整個DataFrame的行中,返回(index, Series)對
    filePath = row['filePath']。# row為字典類型,所以可以用row[key]的形式取到value值
    fileContent = row['fileContent']
    seg_list = jieba.cut(fileContent)
    for seg in seg_list:
        # 去除停用詞及空字符(>0的時候為去處空字符),并且只保留字數(shù)大于1的詞(>1的時候為去處空字符以及計數(shù)小于1的詞)
        if seg not in stopWords['stopword'].values and len(seg.strip())>1:
            segments.append(seg)
            filePaths.append(filePath)
segmentDF = pandas.DataFrame({
    'filePath': filePaths,
    'segment': segments
})

運行結(jié)果如下:(只顯示部分結(jié)果)


*
  • 詞頻統(tǒng)計

# 詞頻統(tǒng)計
segStat = segmentDF.groupby(
    by='segment'
)['segment'].agg({
    '計數(shù)':len
}).reset_index().sort_values(
    '計數(shù)',
    ascending=False  # 降序排列
)

運行結(jié)果如下:(只顯示部分結(jié)果)


*
  • 繪制詞云

# 繪制詞云
wordCloud = WordCloud(
    font_path='data/simhei.ttf',  # 設(shè)置字體為中文字體
    background_color='black'  # 設(shè)置詞云背景顏色
)
words = segStat.set_index('segment').to_dict()  # 設(shè)置segment列為索引,并將DataFrame轉(zhuǎn)化為字典形式
wordCloud.fit_words(words['計數(shù)'])  # 配置詞云
plt.imshow(wordCloud)
plt.show()
plt.close()

運行結(jié)果如下:

*
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容