首頁 > 軟體

Python 使用tf-idf演演算法計算檔案關鍵字權重並生成詞雲的方法

2023-03-17 06:04:59

Python 使用tf-idf演演算法計算檔案關鍵字權重,並生成詞雲

1. 根據tf-idf計算一個檔案的關鍵詞或者短語:

程式碼如下:

注意需要安裝pip install sklean

from re import split
from jieba.posseg import dt
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import Counter
from time import time
import jieba


#pip install sklean


FLAGS = set('a an b f i j l n nr nrfg nrt ns nt nz s t v vi vn z eng'.split())

def cut(text):
    for sentence in split('[^a-zA-Z0-9u4e00-u9fa5]+', text.strip()):
        for w in dt.cut(sentence):
            if len(w.word) > 2 and w.flag in FLAGS:
                yield w.word

class TFIDF:
    def __init__(self, idf):
        self.idf = idf

    @classmethod
    def train(cls, texts):
        model = TfidfVectorizer(tokenizer=cut)
        model.fit(texts)
        idf = {w: model.idf_[i] for w, i in model.vocabulary_.items()}
        return cls(idf)

    def get_idf(self, word):
        return self.idf.get(word, max(self.idf.values()))

    def extract(self, text, top_n=10):
        counter = Counter()
        for w in cut(text):
            counter[w] += self.get_idf(w)
        #return [i[0:2] for i in counter.most_common(top_n)]
        return [i[0] for i in counter.most_common(top_n)]


if __name__ == '__main__':
    t0 = time()
    with open('./nlp-homework.txt', encoding='utf-8')as f:
        _texts = f.read().strip().split('n')
        # print(_texts)
    tfidf = TFIDF.train(_texts)
    # print(_texts)
    for _text in _texts:
        seq_list=jieba.cut(_text,cut_all=True)  #全模式
        # seq_list=jieba.cut(_text,cut_all=False)  #精確模式
        # seq_list=jieba.cut_for_search(_text,)    #搜尋引擎模式
        # print(list(seq_list))
        print(tfidf.extract(_text))
        with open('./resultciyun.txt','a+', encoding='utf-8') as g:
            for i in tfidf.extract(_text):
                g.write(str(i) + " ")
    print(time() - t0)

2. 生成詞雲:

程式碼如下:

  • 注意需要安裝pip install wordcloud
  • 以及為了保證中文字型正常顯示,需要下載SimSun.ttf字型,並且將這個字型包也放在和程式相同的目錄下;
from wordcloud import WordCloud
filename = "resultciyun.txt"
with open(filename) as f:
 resultciyun = f.read()

wordcloud = WordCloud(font_path="simsun.ttf").generate(resultciyun)
# %pylab inline
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

3 最後詞雲的圖片

總結

最後的最後
由本人水平所限,難免有錯誤以及不足之處, 螢幕前的靚仔靚女們 如有發現,懇請指出!

到此這篇關於Python 使用tf-idf演演算法計算檔案關鍵字權重,並生成詞雲的文章就介紹到這了,更多相關Python tf-idf演演算法關鍵字權重並生成詞雲內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com