Python爬虫分析微博热搜关键词(代码已过时,仅供参考)

1,使用到的第三方库
requests
BeautifulSoup 美味汤
worldcloud 词云
jieba 中文分词
matplotlib 绘图
2,代码实现部分

import requests
import wordcloud
import jieba
from bs4 import BeautifulSoup
from matplotlib import pyplot as plt
from pylab import mpl

#设置字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

url = 'https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6'

try:
    #获取数据
    r = requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text,'html.parser')
    data = soup.find_all('a')
    d_list = []
    for item in data:
        d_list.append(item.text)
    words = d_list[4:-11:]
    #中文分词
    result = list(jieba.cut(words[0]))
    for word in words[1::]:
        result.extend(jieba.cut(word))
    redata = []
    for it in result:
        if len(it) <= 1:
            continue
        else:
            redata.append(it)
    result_str = ' '.join(redata)
    #输出词云图
    font = r'C:\Windows\Fonts\simhei.ttf'
    w = wordcloud.WordCloud(font_path=font,width=600,height=400)
    w.generate(result_str)
    w.to_file('微博热搜关键词词云.png')
    key = list(set(redata))
    x,y = [],[]
    #筛选数据
    for st in key:
        count = redata.count(st)
        if count <= 1:
            continue
        else:
            x.append(st)
            y.append(count)
    x.sort()
    y.sort()
    #绘制结果图
    plt.plot(x,y)
    plt.show()
except Exception as e:
    print(e)

3,运行结果
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值