Python 使用tf-idf算法計算文檔關(guān)鍵字權(quán)重并生成詞云的方法
更新時間:2023年03月16日 10:11:52 作者:虛壞叔叔
這篇文章主要介紹了Python 使用tf-idf算法計算文檔關(guān)鍵字權(quán)重,并生成詞云,本文通過實例代碼給大家介紹的非常想詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
Python 使用tf-idf算法計算文檔關(guān)鍵字權(quán)重,并生成詞云
1. 根據(jù)tf-idf計算一個文檔的關(guān)鍵詞或者短語:
代碼如下:
注意需要安裝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-9\u4e00-\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 最后詞云的圖片
總結(jié)
最后的最后
由本人水平所限,難免有錯誤以及不足之處, 屏幕前的靚仔靚女們 如有發(fā)現(xiàn),懇請指出!
到此這篇關(guān)于Python 使用tf-idf算法計算文檔關(guān)鍵字權(quán)重,并生成詞云的文章就介紹到這了,更多相關(guān)Python tf-idf算法關(guān)鍵字權(quán)重并生成詞云內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實現(xiàn)將Excel文件轉(zhuǎn)換為JSON文件
在數(shù)據(jù)處理和分析中,Excel和JSON是兩種常見的數(shù)據(jù)格式,本文將詳細(xì)介紹如何使用Python將Excel文件轉(zhuǎn)換為JSON文件,我們將使用pandas庫,這是一個強(qiáng)大的數(shù)據(jù)分析工具,能夠方便地讀取和處理各種數(shù)據(jù)格式,需要的朋友可以參考下2024-07-07Python操作CouchDB數(shù)據(jù)庫簡單示例
這篇文章主要介紹了Python操作CouchDB數(shù)據(jù)庫簡單示例,本文講解了連接服務(wù)器、創(chuàng)建數(shù)據(jù)庫、創(chuàng)建文檔并插入到數(shù)據(jù)庫等操作實例,需要的朋友可以參考下2015-03-03- python中的easy_install工具,類似于Php中的pear,或者Ruby中的gem,或者Perl中的cpan,那是相當(dāng)?shù)乃嵬崃巳绻胧褂?/div> 2013-02-02
最新評論