文本分析 ※TF-IDF提取關鍵詞及cosine相似度計算

①統計 按需詞頻 (根據業務需求不同,統計條件不同)
具體情況:
文本單一詞 在不同類型文本 出現次數和
-“我愛你 我愛你 我愛你” “我愛你”算一次
-“我愛你 我愛你 我愛你” “我愛你”算三次

文本單一詞 出現總次數:
-“我愛你 我愛你 我愛你” 這句話出現40次 “我愛你”算(1*40)次
-“我愛你 我愛你 我愛你” 這句話出現40次 “我愛你”算(3*40)次

# 構建 統計字典     dict爲在不同類型文本 出現次數和    dict2爲出現總次數
dict={}
dict2={}
#遍歷處理每一條數據
for i in range(len(data)):
    str=data.loc[i, "question"]                       #獲取該條數據對應的文本
    num=int(data.loc[i,"question_count"])             #獲取該文本出現次數
    lis=jieba.cut(str)                        #分詞
    word = []
    for ii in lis:
        #算一次還是算三次的條件。算三次則無需加該判斷
        if ii not in word:            
            word.append(ii)              
    for i in range(len(word)):
        if dict.get(word[i]):
            dict[word[i]]+=1
        else:
            dict[word[i]]=1
        if dict2.get(word[i]):
            dict2[word[i]]+=num
        else:
            dict2[word[i]]=num
#按照出現頻次從大到小排列
d1 = zip(dict.values(), dict.keys())
print(sorted(d, reverse=True))
d2 = zip(dict2.values(), dict2.keys())
print(sorted(d2, reverse=True))

②TF-IDF(Term Frequency-Inverse Document Frequency)提取關鍵詞。
TF-IDF模型中
TF爲詞頻 IDF爲逆文檔頻率 計算公式:
在這裏插入圖片描述在這裏插入圖片描述

#引入包
import numpy as np
import pandas as pd
#定義數據和預處理    如果是中文句子則進行jieba分詞 ③部分有
docA= "The cat sat on my bed"
docB= "The dog sat on my knees"
#詞袋
bowA = docA.split(" ")  
bowB = docB.split(" ")  
wordSet = set(bowA).union(set(bowB))     #構建詞庫,統計

#進行次數統計,統計字典保存詞出現的次數
wordDictA = dict.fromkeys(wordSet, 0)
for word in bowA:
    wordDictA[word] += 1
wordDictB = dict.fromkeys(wordSet, 0)
for word in bowB:
    wordDictB[word] += 1
pd.DataFrame([wordDictA,worldDictB])

#計算詞頻TF   傳入參數:(統計好的字典,詞袋)
def computeTF (wordDict, bow):
    tfDict = {}
    nbowCount =len(bow)
    for word,count in wordDict.items():
        tfDict[word] = count / nbowCount
    return tfDict

#計算逆文檔頻率
def computeIDF(wordDictList):
    idfDict = dict.fromkeys(wordDictList[0], 0)
    N = len(wordDictList)
    import math
    for wordDict in wordDictList:
        #遍歷字典中的每個詞彙,統計Ni
        for word,count in worldDict.items():
            if count>0:
                idfDict[word] +=1
    for word, ni in idfDict.items():
        idfDict[word] = math.log10((N+1)/(ni+1))
    return idfDict
    
#計算TF-IDF
def computeTFIDF(tf, idf):
    tfidf={}
    for word,value in tf.items():
        tfidf[word]=value*idf[word]
    return tfidf

使用:
tfA=computeTF(wordDictA, bowA)                 #A的詞頻
idfs=computeIDF([wordDictA, wordDictB])        #逆文檔頻率
print(computeTFIDF(tfA, idfs))                 #A的TFIDF列表

③cosine相似度判斷函數:

import jieba    依賴包 可以切分中文關鍵詞
#a, b爲需要判斷的兩個字符串
def sim_compute(a, b):
    str1=jieba.cut(a)
    str2=jieba.cut(b)
    #分別將結果轉存爲兩個列表
    word1=[]
    word2=[]
    for i in str1:
        word1.append(i)
    for i in str2:
        word2.append(i)
    #合併word1與word2  
    word = set(word1)
    for value in word2:
        word.add(value)
    #初始化兩個單詞的向量並統計出現次數
    word1_vec={}
    for value in word:
        word1_vec[value]=0
    for value in word1:
        if word1_vec.get(value):
            word1_vec[value]+=1
        else:
            word1_vec[value]=1
    word2_vec={}
    for value in word:
        word2_vec[value]=0
    for value in word2:
        if word2_vec.get(value):
            word2_vec[value]+=1
        else:
            word2_vec[value]=1
    #統計結果轉化爲向量
    vec_1=[]
    vec_2=[]
    for i in word:
        vec_1.append(word1_vec[i])
        vec_2.append(word2_vec[i])
    #公式計算cosine相似度
    sum = 0
    sq1 = 0
    sq2 = 0
    for i in range(len(vec_1)):
        sum += vec_1[i] * vec_2[i]
        sq1 += pow(vec_1[i], 2)
        sq2 += pow(vec_2[i], 2)
    try:
        result = round(float(sum) / (math.sqrt(sq1) * math.sqrt(sq2)), 2)
    except ZeroDivisionError:
        result = 0.0
    return result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章