欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

绘制新浪财经上与“贵州茅台”相关的新闻的词云图。

程序员文章站 2022-05-02 22:01:53
...

1 需求

绘制新浪财经上与“贵州茅台”相关的新闻的词云图。

2 代码实现

import requests
import re
import jieba
import numpy as np
from imageio import imread
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator


headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'}
url = 'https://search.sina.com.cn/news?q=贵州茅台&c=news&sort=time'
res = requests.get(url=url, headers=headers).text
try:
    res = res.encode('ISO-8859-1').decode('utf-8')
except:
    try:
        res = res.encode('ISO-8859-1').decode('gbk')
    except:
        res = res
p_title = '<h2><a href.*?target="_blank">(.*?)</a>'
title = re.findall(p_title, res)

for index in range(len(title)):
    title[index] = re.sub('<.*?>', '', title[index]).strip()
content = ' '.join(title)
contents = jieba.cut(content)
reports = []
for content in contents:
    if len(content) >= 2:
        reports.append(content)

# 按特定形状和特定颜色绘制词云图
# 获取词云图的形状蒙版
background_pic = '酒.jpg'
images = Image.open(background_pic)
maskImages = np.array(images)

# 按照形状蒙版绘制词云图
content = ' '.join(reports)
wc = WordCloud(
    font_path='simhei.ttf',
    background_color='white',
    width=1000,
    height=600,
    mask=maskImages
).generate(content)

# 修改词云图的颜色
back_color = imread(background_pic, format=None)
image_colors = ImageColorGenerator(back_color)
wc.recolor(color_func=image_colors)

wc.to_file('词云图+自定义+颜色.png')