天天看點

寫一個TF-IDF模型

這個小項目是跟一位廣工的小夥伴一起完成的,他負責提供資料和這個模型的理論,沒辦法,誰讓咱數學底子薄呢,我就是負責一下代碼實作就完事了

  1. 模型理論

    這個模型的基礎理論其實不難

    假設我有一千篇論文,通過資料清洗,分詞等操作,我得到了關鍵詞資料。

    然後從這些關鍵詞中,再次去找關鍵詞。常理來說,一個詞出現的頻率越高那麼這個詞就越關鍵。然如果隻有這一篇論文出現了這麼一個詞,而且滿篇都是這一個詞,這個詞被惡意刷屏了,怎麼辦。那麼我們就在引入一個量,log(總文章/總文章中含有這個詞的文章數),咱也不曉得這個模型的大佬是怎麼想的用這個方法,可能這就是奇才吧。然後我們把這個詞頻和那個數相乘,那麼就得到了我們需要的量 TF-IDF模型量,通過這個量,我們得知哪個關鍵字最關鍵。

  2. 代碼實驗

    來來來,直接代碼搞一波

    首先做個聲明,所有的資料已經清洗,分詞完畢,統一放在一個txt檔案中,那麼有人問了,都放在了同一個檔案中,那怎麼算後面那個量呢。很簡單,我們可以把擷取的這個大數組分成若幹個小數組,模拟有這麼多篇論文,因為是實驗,總有些不嚴謹的地方。

```python
from collections import Counter

import math
import operator

"""
讀取txt函數
path:txt路徑
encod:編碼
"""
def read_txt(path,encod):
    file = open(path, 'r',encoding = encod)
    return file

"""
将已經分好詞的文本檔案轉換成數組
"""
def txtToList(file):
    list = []
    num = 0
    contents = file.readlines()
    for content in contents:
        content = content.split(',')
        for word in content:
            list.append(word)
            num = num + 1
    print("目前文本詞彙個數: ",num)
    return list,num

"""
将list資料存入txt檔案中
"""
def listToTxt(put_list,fileName):
    f = open(fileName, "w",encoding="utf-8")
    for list_mem in put_list:
        f.write(list_mem + ",")
    f.close()


"""
将數組按照等量劃分
"""
def arr_size(arr,size):
    s=[]
    for i in range(0,len(arr)+1,size):
        c=arr[i:i+size]
        s.append(c)
    return s


# 計算詞頻
def func_counter(word_list):
    count_result = Counter(word_list)
    return count_result


# 尋找某個關鍵詞的詞數
def fidc_wf(word,wfs_Dict):
    word_num = wfs_Dict[word]
    return word_num
#關鍵詞在這篇文章中是否出現
def findw_article(word,article):
    for str in article:
        if( word == str):
            return True
    return False


# 查出包含該詞的文檔數
def wordinfilecount(i_word, put_lists):
    count = 0  # 計數器
    for train_list in put_lists:
        if (findw_article(i_word, train_list)):
            count = count + 1
    #print("關鍵字在" + str(count) + "篇q文章中出現過")
    return count


# 計算TF-IDF,并傳回字典
def tf_idf(dataList,putLists,num):
    tf = 0
    idf = 0
    dic = func_counter(dataList) #擷取每個關鍵詞的出現次數
    outdic = dic
    for word in dic.keys():
        tf = fidc_wf(word,dic)/num #計算關鍵詞詞頻
        idf = math.log(len(putLists)/(wordinfilecount(word,putLists)+1)) #計算idf
        tfidf = tf * idf # 計算綜合
        outdic[word] = tfidf #寫入鍵值對
    orderdic = sorted(outdic.items(), key=operator.itemgetter(1), reverse=True)  # 給字典排序
    return orderdic



# 讀取檔案
file = read_txt(自己的檔案路徑,'utf-8')
# 将檔案轉化為list數組
list,num = txtToList(file)
# 将數組按照1000的個數劃分成若幹個小數組
put_lists = arr_size(list,1000)

#調用主函數
print(tf_idf(list,put_lists,num))