lsekfe 发表于 2023-6-21 11:11:28

如何使用Python爬取关键字并同时生成图片

比如一则新闻,如下图所示:
http://www.51testing.com/attachments/2023/06/15326825_202306161618024H7cb.png
  解决思路
  1、先爬取新闻中的所有文字
  2、再把所有的文字分割,使之成为一个个的字
  3、将出现的字进行统计,统计出次数靠前的10位
  4、再生成词云图或饼图
  请看以下代码:
import jieba as jieba
import requests
from bs4 import BeautifulSoup
from pyecharts.charts import WordCloud, Pie

if __name__ == "__main__":
   headers = {
         "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
   }
   url="https://new.qq.com/rain/a/20230315A08LAK00"
   res_html = requests.get(url, headers=headers).text
   # print(res_html)

   # 创建一个BeautifulSoup对象。对获取的网页进行过滤,获取其内容
   soup = BeautifulSoup(res_html, "lxml")
   # 获取文章的文字
   txt = soup.select(".content-article").text
   # print(txt)
   # 对文章进行分割
   words = jieba.lcut(txt)

   # 统计每个词语出现的次数
   counts = {}
   for word in words:
         if len(word) == 1:
             continue
         else:
             counts = counts.get(word, 0) + 1
   # 获取出现次数最多的前10个词语
   # counts.items -----> counts里面的所有项
   # a ------> counts里面的每一项
   sort_data = sorted(counts.items(), key=lambda a: a, reverse=True)[:10]

   # 词云图
   wc = WordCloud()
   wc.add("", sort_data, word_size_range=)
   wc.render("1.html")

   # 饼图
   pip = Pie()
   pip.add(
         series_name="次数",
         data_pair=sort_data
   )
   pip.render("2.html")


  结果
  一起看一下运行效果:
http://www.51testing.com/attachments/2023/06/15326825_202306161618021KXxU.png
http://www.51testing.com/attachments/2023/06/15326825_202306161618022N92M.png
  饼图:
http://www.51testing.com/attachments/2023/06/15326825_202306161618023zWrd.png

页: [1]
查看完整版本: 如何使用Python爬取关键字并同时生成图片