日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

用Python玩转词云

發(fā)布時間:2025/4/16 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用Python玩转词云 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

第一步:引入相關(guān)的庫包:

#coding:utf-8 __author__ = 'Administrator' import jieba #分詞包 import numpy #numpy計算包 import codecs #codecs提供的open方法來指定打開的文件的語言編碼,它會在讀取的時候自動轉(zhuǎn)換為內(nèi)部unicode import pandas import matplotlib.pyplot as plt %matplotlib inlinefrom wordcloud import WordCloud#詞云包

第二部:導入分好詞的西游記txt文件:

file=codecs.open(u"西游記.txt",'r','utf-8') content=file.read() file.close() jieba.load_userdict(u"紅樓夢分詞.txt") segment=[] segs=jieba.cut(content) for seg in segs:if len(seg)>1 and seg!='\r\n':segment.append(seg)

第三部:統(tǒng)計分詞結(jié)果并去掉停用詞:

segmentDF=pandas.DataFrame({'segment':segment}) segmentDF.head() stopwords=pandas.read_csv("stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'])#quoting=3全不引用 stopwords.head() segmentDF=segmentDF[~segmentDF.segment.isin(stopwords.stopword)] wyStopWords=pandas.Series(['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','便','','','','','','','','','','" "']) segmentDF=segmentDF[~segmentDF.segment.isin(wyStopWords)]

第四部:統(tǒng)計詞頻:

segStat=segmentDF.groupby(by=['segment'])['segment'].agg({"計數(shù)":numpy.size}) segStat=segStat.reset_index().sort(columns="計數(shù)",ascending=False) segStat

?

第五步:顯示詞云

wordcloud=WordCloud(font_path="simhei.ttf",background_color="black")
wordcloud=wordcloud.fit_words(segStat.head(1000).itertuples(index=False))
plt.imshow(wordcloud)

?

?

第六步:自定義詞云形狀

from scipy.misc import imread import matplotlib.pyplot as plt from wordcloud import WordCloud,ImageColorGenerator bimg=imread('3.jPG') wordcloud=WordCloud(background_color="white",mask=bimg,font_path='C:\Windows\Fonts\simhei.ttf') wordcloud=wordcloud.fit_words(segStat.head(39769).itertuples(index=False)) bimgColors=ImageColorGenerator(bimg) plt.axis("off") plt.imshow(wordcloud.recolor(color_func=bimgColors)) plt.show()

?

?

轉(zhuǎn)載于:https://www.cnblogs.com/wuchuanying/p/6225179.html

總結(jié)

以上是生活随笔為你收集整理的用Python玩转词云的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。