本文小编为大家详细介绍“Python怎么使用tf-idf算法计算文档关键字权重并生成词云”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python怎么使用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-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)
代码如下:
注意需要安装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()
读到这里,这篇“Python怎么使用tf-idf算法计算文档关键字权重并生成词云”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。