增补博客 第九篇 python 图书评论数据分析与可视化

三尺非寒  金牌会员 | 2024-6-14 10:22:04 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 901|帖子 901|积分 2703

【标题形貌】豆瓣图书评论数据爬取。以《平常的天下》、《都挺好》等为分析对象,编写程序爬取豆瓣读书上针对该图书的短评信息,要求:

(1)对前3页短评信息进行跨页连续爬取;

(2)爬取的数据包含用户名、短评内容、评论时间、评分和点赞数(有效数);

(3)能够根据选择的排序方式(热门或最新)进行爬取,并分别针对热门和最新排序,输出前10位短评信息(包括用户名、短评内容、评论时间、评分和点赞数)。

(4)根据点赞数的多少,按照从多到少的顺序将排名前10位的短评信息输出;

(5附加)联合中文分词和词云天生,对前3页的短评内容进行文本分析:按照词语出现的次数从高到低排序,输出前10位排序结果;并天生一个属于自己的词云图形。
【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的解释。
 
  1. import re
  2. from collections import Counter
  3. import requests
  4. from lxml import etree
  5. import pandas as pd
  6. import jieba
  7. import matplotlib.pyplot as plt
  8. from wordcloud import WordCloud
  9. headers = {
  10.     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39"
  11. }
  12. comments = []
  13. words = []
  14. def regex_change(line):
  15.     # 前缀的正则
  16.     username_regex = re.compile(r"^\d+::")
  17.     # URL,为了防止对中文的过滤,所以使用[a-zA-Z0-9]而不是\w
  18.     url_regex = re.compile(r"""
  19.         (https?://)?
  20.         ([a-zA-Z0-9]+)
  21.         (\.[a-zA-Z0-9]+)
  22.         (\.[a-zA-Z0-9]+)*
  23.         (/[a-zA-Z0-9]+)*
  24.     """, re.VERBOSE | re.IGNORECASE)
  25.     # 剔除日期
  26.     data_regex = re.compile(u"""        #utf-8编码
  27.         年 |
  28.         月 |
  29.         日 |
  30.         (周一) |
  31.         (周二) |
  32.         (周三) |
  33.         (周四) |
  34.         (周五) |
  35.         (周六)
  36.     """, re.VERBOSE)
  37.     # 剔除所有数字
  38.     decimal_regex = re.compile(r"[^a-zA-Z]\d+")
  39.     # 剔除空格
  40.     space_regex = re.compile(r"\s+")
  41.     regEx = "[\n”“|,,;;''/?! 。的了是]"  # 去除字符串中的换行符、中文冒号、|,需要去除什么字符就在里面写什么字符
  42.     line = re.sub(regEx, "", line)
  43.     line = username_regex.sub(r"", line)
  44.     line = url_regex.sub(r"", line)
  45.     line = data_regex.sub(r"", line)
  46.     line = decimal_regex.sub(r"", line)
  47.     line = space_regex.sub(r"", line)
  48.     return line
  49. def getComments(url):
  50.     score = 0
  51.     resp = requests.get(url, headers=headers).text
  52.     html = etree.HTML(resp)
  53.     comment_list = html.xpath(".//div[@class='comment']")
  54.     for comment in comment_list:
  55.         status = ""
  56.         name = comment.xpath(".//span[@class='comment-info']/a/text()")[0]  # 用户名
  57.         content = comment.xpath(".//p[@class='comment-content']/span[@class='short']/text()")[0]  # 短评内容
  58.         content = str(content).strip()
  59.         word = jieba.cut(content, cut_all=False, HMM=False)
  60.         time = comment.xpath(".//span[@class='comment-info']/a/text()")[1]  # 评论时间
  61.         mark = comment.xpath(".//span[@class='comment-info']/span/@title")  # 评分
  62.         if len(mark) == 0:
  63.             score = 0
  64.         else:
  65.             for i in mark:
  66.                 status = str(i)
  67.             if status == "力荐":
  68.                 score = 5
  69.             elif status == "推荐":
  70.                 score = 4
  71.             elif status == "还行":
  72.                 score = 3
  73.             elif status == "较差":
  74.                 score = 2
  75.             elif status == "很差":
  76.                 score = 1
  77.         good = comment.xpath(".//span[@class='comment-vote']/span[@class='vote-count']/text()")[0]  # 点赞数(有用数)
  78.         comments.append([str(name), content, str(time), score, int(good)])
  79.         for i in word:
  80.             if len(regex_change(i)) >= 2:
  81.                 words.append(regex_change(i))
  82. def getWordCloud(words):
  83.     # 生成词云
  84.     all_words = []
  85.     all_words += [word for word in words]
  86.     dict_words = dict(Counter(all_words))
  87.     bow_words = sorted(dict_words.items(), key=lambda d: d[1], reverse=True)
  88.     print("热词前10位:")
  89.     for i in range(10):
  90.         print(bow_words[i])
  91.     text = ' '.join(words)
  92.     w = WordCloud(background_color='white',
  93.                      width=1000,
  94.                      height=700,
  95.                      font_path='simhei.ttf',
  96.                      margin=10).generate(text)
  97.     plt.show()
  98.     plt.imshow(w)
  99.     w.to_file('wordcloud.png')
  100. print("请选择以下选项:")
  101. print("   1.热门评论")
  102. print("   2.最新评论")
  103. info = int(input())
  104. print("前10位短评信息:")
  105. title = ['用户名', '短评内容', '评论时间', '评分', '点赞数']
  106. if info == 1:
  107.     comments = []
  108.     words = []
  109.     for i in range(0, 60, 20):
  110.         url = "https://book.douban.com/subject/10517238/comments/?start={}&limit=20&status=P&sort=new_score".format(
  111.             i)  # 前3页短评信息(热门)
  112.         getComments(url)
  113.     df = pd.DataFrame(comments, columns=title)
  114.     print(df.head(10))
  115.     print("点赞数前10位的短评信息:")
  116.     df = df.sort_values(by='点赞数', ascending=False)
  117.     print(df.head(10))
  118.     getWordCloud(words)
  119. elif info == 2:
  120.     comments = []
  121.     words=[]
  122.     for i in range(0, 60, 20):
  123.         url = "https://book.douban.com/subject/10517238/comments/?start={}&limit=20&status=P&sort=time".format(
  124.             i)  # 前3页短评信息(最新)
  125.         getComments(url)
  126.     df = pd.DataFrame(comments, columns=title)
  127.     print(df.head(10))
  128.     print("点赞数前10位的短评信息:")
  129.     df = df.sort_values(by='点赞数', ascending=False)
  130.     print(df.head(10))
  131.     getWordCloud(words)
复制代码
  

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

三尺非寒

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表