作者:虚坏叔叔
博客:https://xuhss.com
早餐店不会开到晚上,想吃的人早就来了!😄
代码如下:
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 skleanFLAGS = 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.wordclass TFIDF:def __init__(self, idf):self.idf = idf@classmethoddef 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 WordCloudfilename = "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实战微信订餐小程序 🧡 | 进阶级 | 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。 |
💛Python量化交易实战 💛 | 入门级 | 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 |
❤️ C++ QT结合FFmpeg实战开发视频播放器❤️ | 难度偏高 | 分享学习QT成品的视频播放器源码,需要有扎实的C++知识! |
💚 游戏爱好者九万人社区💚 | 互助/吹水 | 九万人游戏爱好者社区,聊天互助,白嫖奖品 |
💙 Python零基础到入门 💙 | Python初学者 | 针对没有经过系统学习的小伙伴,核心目的就是让我们能够快速学习Python的知识以达到入门 |
关注下面卡片即刻获取更多编程知识,包括各种语言学习资料,上千套PPT模板和各种游戏源码素材等等资料。更多内容可自行查看哦!