欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python爬虫分析微博热搜关键词的实现代码

时间:2021-06-29 08:28:18|栏目: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,运行结果

在这里插入图片描述
在这里插入图片描述

上一篇:PyTorch学习笔记之回归实战

栏    目:Python代码

下一篇:python3 批量获取对应端口服务的实例

本文标题:Python爬虫分析微博热搜关键词的实现代码

本文地址:http://www.codeinn.net/misctech/149954.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有