用Python玩转词云
生活随笔
收集整理的這篇文章主要介紹了
用Python玩转词云
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一步:引入相關的庫包:
#coding:utf-8 __author__ = 'Administrator' import jieba #分詞包 import numpy #numpy計算包 import codecs #codecs提供的open方法來指定打開的文件的語言編碼,它會在讀取的時候自動轉換為內部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)第三部:統計分詞結果并去掉停用詞:
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)]第四部:統計詞頻:
segStat=segmentDF.groupby(by=['segment'])['segment'].agg({"計數":numpy.size}) segStat=segStat.reset_index().sort(columns="計數",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()?
?
轉載于:https://www.cnblogs.com/wuchuanying/p/6225179.html
總結
以上是生活随笔為你收集整理的用Python玩转词云的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EntityFramework Core
- 下一篇: android系统release签名