jieba自定义idf库


先建个list,名字叫:data_content
里面的内容如上图。要把数据处理成上面那样的
先分词、过滤。

最后引入如下代码:

import math
idf_dic = {}

#data_content是分析文本
doc_count  = len(data_content) # 总共有多少篇文章

for i in range(len(data_content)):
    new_content = data_content[i].split(' ')
    for word in set(new_content):
        if len(word) > 1:
            idf_dic[word] = idf_dic.get(word, 0.0) + 1.0
        # 此时idf_dic的v值:有多少篇文档有这个词,就是多少
for k,v in idf_dic.items():
    w = k
    p = '%.10f' % (math.log(doc_count / (1.0 + v))) # 结合上面的tf-idf算法公式
    if w > u'\u4e00' and w<=u'\u9fa5': # 判断key值全是中文
        idf_dic[w] = p
with open('wdic.txt','w',encoding='utf-8') as f:
    for k in idf_dic:
        if k != '\n' :
#             print(k,type(k),idf_dic[k],type(idf_dic[k]))

            f.write(str(k) + ' ' + str(idf_dic[k]) + '\n') #写入txt文件,注意utf-8,否则jieba不认

最后一步,引用

jieba.analyse.set_stop_words("stopwords.txt")   #载入停用词
jieba.analyse.set_idf_path("wdic.txt");   #载入自定义idf库

with open(r'zhengce.txt','r',encoding='utf8') as f:
    lines = f.read()
tags = jieba.analyse.extract_tags(lines, topK=10)
print(",".join(tags))

posted on 2021-02-04 13:04  耀扬  阅读(1040)  评论(0编辑  收藏  举报

导航