python wordcloud 詞云萬能教程

2021-09-25 00:27:24 字數 2049 閱讀 1137

# -*- coding: utf-8 -*-

"""created on 2019/5/22 10:18

@author: johnson

@email:[email protected]

@file: wordcloud教程.py

"""from os import path

from scipy.misc import imread

from wordcloud import wordcloud, stopwords

import matplotlib.pyplot as plt

def wordcount(filename):

'''簡單計算詞頻的函式

:param filename: 檔名

:return: 詞頻

'''wordcount = {}

file = open(filename,'r')

while true:

line = file.readline()

if line:

wordlist = line.split(',[')

if len(wordlist) == 1: continue

wordlist = wordlist[1].split('],')[0].split(',')

for word in wordlist:

word = word.replace(' ', '').replace("'", '')

if word in wordcount.keys():

wordcount[word] = wordcount[word]+1

else:

wordcount[word] = 1

else:

break

return [(k, wordcount[k]) for k in wordcount.keys()]

def generatecloud(filename,imagename,cloudname,fontname):

'''生成標籤雲的函式

'''coloring = imread(imagename) # 讀取背景

wc = wordcloud(background_color="white", # 背景顏色max_words=2000,# 詞云顯示的最大詞數

mask=coloring, # 設定背景

stopwords=stopwords, # 停止詞

font_path=fontname, # 相容中文字型

max_font_size=150) # 字型最大值

#計算好詞頻後使用generate_from_frequencies函式生成詞云

#txtfreq例子為[('詞a', 100),('詞b', 90),('詞c', 80)]

txtfreq = wordcount(filename)

wc.generate_from_frequencies(txtfreq)

# 生成

plt.imshow(wc)

plt.axis("off")

# 繪製詞云

plt.figure()

# 儲存詞云

wc.to_file(cloudname)

if __name__ == '__main__':

d = path.dirname(__file__) # 獲取當前檔案路徑

fontname = path.join(d, 'msyh.ttf') # 中文字型路徑

filename = path.join(d, '廣州.txt') # txt檔案路徑

imagename = path.join(d, "circle.jpg") # 背景路徑

cloudname = path.join(d, "cloud.png") # 標籤雲路徑

generatecloud(filename, imagename, cloudname, fontname)

python WordCloud詞云安裝

解決辦法 先安裝wrapt 1.10.11 cp36 cp36m win amd64.whl 再安裝wordcloud 1.3.2 cp36 cp36m win amd64.whl 成功驗證 發現成功匯入wordcloud的包 測試 fromwordcloudimportwordcloud f op...

Python wordcloud庫的使用

1 wordcloud庫基本介紹 1 wordcloud庫概述 wordcloud是優秀的詞云展示第三方庫 詞云以詞語為基本單位,更加直觀和藝術的展示文字 2 wordcloud庫的安裝 cmd命令列 pip install wordcloud 2 wordcloud庫使用說明 1 wordclou...

Python wordcloud庫學習小結

w wordcloud.wordcloud 方法描述例子 w.generate txt 向wordcloud物件w中載入文字txt w.generate python and wordcloud w.to file filename 將詞云輸出為影象檔案,png或.jpg格式 w.to file o...