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))


免責聲明!

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



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