数据挖掘——关键字提取—sklearn的实际应用

前面的步骤都相似

#构建语料库

#使用jieba包进行分词,并将分词结果用空格分隔后再传回分词列表

zh = re.compile(u'[\u4e00-\u9fa5]+')    #中文的正则表达式
for seg in segs:
        if zh.search(seg):  #只匹配中文分词
            segments.append(seg)
    filepath.append(filePath)
 #使用空格将符合要求的分词隔开,然后放回语料库中,而不是得到分词和路径的矩阵
    row['fileContent'] = ' '.join(segments) 

#导入sklearn包中计算TF-IDF的模块,可以将停用词以参数的形式传入CountVectorizer模块

得到numpy类的数据结构,需要进行转换

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
skcount = CountVectorizer(
        stop_words=list(stopwords['stopword'].values),
        min_df=0,
        token_pattern=r'\b\w+\b') #分词的正则表达式

text = skcount.fit_transform(corpos['fileContent'])

trans = TfidfTransformer()
tfidf = trans.fit_transform(text)

#将得到的TF-IDF结构转换成数组的形式,并得到关键字numpy类的数据结构

#按行转换成数组,并排序,取tfidf值前5的元素的位置
sort = np.argsort(tfidf.toarray(),axis=1)[:,-5:] 
#获取该位置所对应的列名,即分词关键字
names = skcount.get_feature_names() 
keywords = pd.Index(names)[sort].values #非数组

#将关键字按数据框的格式进行输出,得到最终结果

tagDF = pd.DataFrame({
        '文件路径':corpos.filePath,
        '文本内容':corpos.fileContent,
        '关键字1':keywords[:,0], 
        '关键字2':keywords[:,1],
        '关键字3':keywords[:,2],
        '关键字4':keywords[:,3],
        '关键字5':keywords[:,4]})

猜你喜欢

转载自www.cnblogs.com/rix-yb/p/9704308.html
今日推荐