Python數據挖掘-詞頻統計-實現


詞頻:某個詞在該文檔中出現的內容

 

1、語料庫搭建

import jieba jieba.load_userdict("D:\\Python\\Python數據挖掘\\Python數據挖掘實戰課程課件\\2.2\\金庸武功招式.txt") import os import os.path import codecs filePaths=[] fileContents=[] for root,dirs,files in os.walk("D:\\Python\\Python數據挖掘\\Python數據挖掘實戰課程課件\\2.2\\SogouC.mini\\Sample"): for name in files: filePath=os.path.join(root,name) filePaths.append(filePath) f=codecs.open(filePath,"r","utf-8") fileContent=f.read() f.close() fileContents.append(fileContent) import pandas corpos=pandas.DataFrame({ "filePath":filePaths, "fileContent":fileContents}) #分詞來源哪個文章
import jieba segments=[] filePaths=[] for index,row in corpos.iterrows(): filePath=row["filePath"] fileContent=row["fileContent"] segs=jieba.cut(fileContent) for seg in segs: segments.append(seg) filePaths.append(filePath) segmentDataFrame=pandas.DataFrame({ "segment":segments, "filepath":filePaths})

 

2、詞頻統計

import numpy #進行詞頻統計 #by是要分組的列,[]是要統計的列
segStat=segmentDataFrame.groupby( by="segment" )["segment"].agg({ "計數":numpy.size }).reset_index().sort(columns=["計數"], #重新設置索引,再根據計數進行逆序排序 ascending=False)

by=[“列名”]后面跟着的是要分組的列,根據方括號里面的列的內容來進行統計;

第二個[]是要統計的列,在分組的列的基礎上進行統計的列,可以是它自己本身

 

 

3、移除停用詞,由於統計的詞語很多是我們不需要的,所以需要移除

stopwords=pandas.read_csv( "D:\\Python\\Python數據挖掘\\Python數據挖掘實戰課程課件\\2.3\\StopwordsCN.txt", #改文件中包含停用詞 encoding="utf-8", index_col=False) fSegStat=segStat[ ~segStat.segment.isin(stopwords.stopword)]

所用方法為isin(),然后在取反~

 

 

第二種分詞方法:

import jieba segments=[] filePaths=[] for index,row in corpos.iterrows(): filePath=row["filePath"] fileContent=row["fileContent"] segs=jieba.cut(fileContent) for seg in segs: if seg not in stopwords.stopword.values and len(seg.strip())>0: segments.append(seg) filePaths.append(filePath) segmentDataFrame=pandas.DataFrame({ "segment":segments, "filePath":filePaths}) segStat=segmentDataFrame.groupby( by="segment" )["segment"].agg({ "計數":numpy.size }).reset_index().sort( columns=["計數"], ascending=False)

 

第二種分詞方法,是在jieba分詞后,通過if判斷,篩選除了不在stopwords里面的分詞,然后在再輸出為數據框,再統計計數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM