第三方库 wordcloud

pip install wordcloud

指定镜像源:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple wordcloud

文档:https://amueller.github.io/word_cloud/index.html

wordcloud.WordCloud()

案例 1:”政府工作报告爬取与词云绘制“

python 13 行
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import urllib.request
from bs4 import BeautifulSoup
from wordcloud import WordCloud

url = "https://www.gov.cn/zhuanti/2021lhzfgzbg/index.htm"
response = urllib.request.urlopen(url)
html = response.read().decode("utf-8")

soup = BeautifulSoup(html, "html.parser")
content = soup.find("div", class_="zhj-bbqw-cont").text

w = WordCloud(font_path="/Fonts/simhei.ttf").generate(content)
w.to_file("政府工作报告y1.png")

简单词云绘制

算法流程

实例 1:英文词云

python 4 行
1
2
3
4
from wordcloud import WordCloud
text = "Life is short, I use Python"
w = WordCloud().generate(text)
w.to_file('usePython.png')

wordcloud 是如何将文本转化为词云呢?

  • 文本分词:默认以空格分隔各词
  • 词频统计:统计单词出现次数,并且初步过滤
    • stopwords=set('dog')设置要去除的停用词。以字符串或者集合作为接收参数。如不设置将使用内置默认的停动词词库
  • 字号配置:根据词频进行字号配置
  • 云图布局:配置云图的颜色、字体、尺寸等

WordCloud 对象常用参数

实例 2:英文词云-优化

python 8 行
1
2
3
4
5
6
7
8
from wordcloud import WordCloud,STOPWORDS
text = "Life is short, I use Python"

w = WordCloud(background_color="white",
              stopwords=STOPWORDS.add("use"))

w = w.generate(text)
w.to_file("usePython.png")

实例 3:中医药方词云绘制

CNMed.txt

python 4 行
1
2
3
4
清热凉血解毒药:石膏、菊花、知母、柴胡、银胡、白薇、决明子、夏枯草、栀子、芦根、牛黄、玄参、黄芩
、黄连、黄柏、龙胆草、金银花、连翘。蒲公英、白头翁、与齿范、柴草根、青箱子、西瓜、虎耳草
祛风湿药:姜活、独活、五加皮、木瓜、威灵仙、白芷、秦艽、稀签草、苍耳子、桑枝、臭梧桐
发散风寒药:麻黄、根、桂枝、肉桂、紫苏叶、梗,细辛、防风、荆芥、生姜、干姜法、炮姜、葱白、辛夷
  • 中文字体显示问题
    • font_path指定文本文件的路径,默认 None
    • w = WordCloud(font_path="/Fonts/simhei.ttf")
python 5 行
1
2
3
4
5
from wordcloud import WordCloud
text = open(r'E:\OneDrive\桌面\Python\CNMed.txt', encoding='utf-8').read()
font = '/Fonts/simhei.ttf'
wcloud = WordCloud(font_path = font).generate(text)
wcloud.to_file('CNMed.png')

实例 4:政府工作报告词云绘制

词频统计

文本分词

将文本拆分成独立的字词以便于后续使用

wordcloud文本分词:默认以空格分隔各词

wordcloud词频统计:统计单词出现次数,初步过滤

中文分词

案例

英文分词

案例

词云绘制改进