jieba是比較常用python的分詞庫,這裡簡單介紹它的基本用法。
import jieba
cut1 = jieba.cut("我來自湖北武漢,我現在在上海工作。", cut_all=True)
[i for i in cut1]從網上下載一篇文章,分析該文章詞頻結構。這裡用了collections包,直接統計詞頻。
from collections import Counter
cut2=open('baogao.txt').read()
words = jieba.cut(cut2) # 使用精簡模式對文本進行分詞
counts = [] # 獲取其中的詞
for word in words:
if len(word)>=4:
counts.append(word)
Counter(counts).most_common(20)#查看排前20的詞from wordcloud import WordCloud
import matplotlib.pyplot as plt
stop_words=['的','得']#停用詞,以後可以增加
# 使用WordCloud生成詞雲
word_cloud = WordCloud(font_path="simsun.ttc", # 設置詞雲字體
background_color="white", # 詞雲圖的背景顏色
stopwords=stop_words,# 去掉的停詞
collocations=False) #,去掉詞雲中的重複詞,如果不填false,後面的詞雲圖可能出現重複詞。
text_cut = ' '.join(counts)
word_cloud.generate(text_cut)
plt.subplots(figsize=(12,8))
plt.imshow(word_cloud)
plt.axis("off")也可以用PIL包,把詞雲圖製作成自己需要展示的圖片形狀,也很簡單,導入PIL包,畫圖設置相應的背景即可。
所謂擅長,就是日復一日。