首页 > 其他分享 >2024.5.30

2024.5.30

时间:2024-06-13 15:55:55浏览次数:13  
标签:comment 10 2024.5 短评 30 regex words line

8-2 【Python0026】图书评论数据分析与可视化 分数 10 作者 doublebest 单位 石家庄铁道大学

【题目描述】豆瓣图书评论数据爬取。以《平凡的世界》、《都挺好》等为分析对象,编写程序爬取豆瓣读书上针对该图书的短评信息,要求:

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

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

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

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

(5附加)结合中文分词和词云生成,对前3页的短评内容进行文本分析:按照词语出现的次数从高到低排序,输出前10位排序结果;并生成一个属于自己的词云图形。

【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。

import re

from collections import Counter

 

import requests

from lxml import etree

import pandas as pd

import jieba

import matplotlib.pyplot as plt

from wordcloud import WordCloud

 

headers = {

    "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"

}

 

comments = []

words = []

 

 

def regex_change(line):

    # 前缀的正则

    username_regex = re.compile(r"^\d+::")

    # URL,为了防止对中文的过滤,所以使用[a-zA-Z0-9]而不是\w

    url_regex = re.compile(r"""

        (https?://)?

        ([a-zA-Z0-9]+)

        (\.[a-zA-Z0-9]+)

        (\.[a-zA-Z0-9]+)*

        (/[a-zA-Z0-9]+)*

    """, re.VERBOSE | re.IGNORECASE)

    # 剔除日期

    data_regex = re.compile(u"""        #utf-8编码

        年 |

        月 |

        日 |

        (周一) |

        (周二) |

        (周三) |

        (周四) |

        (周五) |

        (周六)

    """, re.VERBOSE)

    # 剔除所有数字

    decimal_regex = re.compile(r"[^a-zA-Z]\d+")

    # 剔除空格

    space_regex = re.compile(r"\s+")

    regEx = "[\n”“|,,;;''/?! 。的了是]"  # 去除字符串中的换行符、中文冒号、|,需要去除什么字符就在里面写什么字符

    line = re.sub(regEx, "", line)

    line = username_regex.sub(r"", line)

    line = url_regex.sub(r"", line)

    line = data_regex.sub(r"", line)

    line = decimal_regex.sub(r"", line)

    line = space_regex.sub(r"", line)

    return line

 

 

def getComments(url):

    score = 0

    resp = requests.get(url, headers=headers).text

    html = etree.HTML(resp)

    comment_list = html.xpath(".//div[@class='comment']")

    for comment in comment_list:

        status = ""

        name = comment.xpath(".//span[@class='comment-info']/a/text()")[0]  # 用户名

        content = comment.xpath(".//p[@class='comment-content']/span[@class='short']/text()")[0]  # 短评内容

        content = str(content).strip()

        word = jieba.cut(content, cut_all=False, HMM=False)

        time = comment.xpath(".//span[@class='comment-info']/a/text()")[1]  # 评论时间

        mark = comment.xpath(".//span[@class='comment-info']/span/@title")  # 评分

        if len(mark) == 0:

            score = 0

        else:

            for i in mark:

                status = str(i)

            if status == "力荐":

                score = 5

            elif status == "推荐":

                score = 4

            elif status == "还行":

                score = 3

            elif status == "较差":

                score = 2

            elif status == "很差":

                score = 1

        good = comment.xpath(".//span[@class='comment-vote']/span[@class='vote-count']/text()")[0]  # 点赞数(有用数)

        comments.append([str(name), content, str(time), score, int(good)])

        for i in word:

            if len(regex_change(i)) >= 2:

                words.append(regex_change(i))

 

 

def getWordCloud(words):

    # 生成词云

    all_words = []

    all_words += [word for word in words]

    dict_words = dict(Counter(all_words))

    bow_words = sorted(dict_words.items(), key=lambda d: d[1], reverse=True)

    print("热词前10位:")

    for i in range(10):

        print(bow_words[i])

    text = ' '.join(words)

 

    w = WordCloud(background_color='white',

                     width=1000,

                     height=700,

                     font_path='simhei.ttf',

                     margin=10).generate(text)

    plt.show()

    plt.imshow(w)

    w.to_file('wordcloud.png')

 

 

print("请选择以下选项:")

print("   1.热门评论")

print("   2.最新评论")

info = int(input())

print("前10位短评信息:")

title = ['用户名', '短评内容', '评论时间', '评分', '点赞数']

if info == 1:

    comments = []

    words = []

    for i in range(0, 60, 20):

        url = "https://book.douban.com/subject/10517238/comments/?start={}&limit=20&status=P&sort=new_score".format(

            i)  # 前3页短评信息(热门)

        getComments(url)

    df = pd.DataFrame(comments, columns=title)

    print(df.head(10))

    print("点赞数前10位的短评信息:")

    df = df.sort_values(by='点赞数', ascending=False)

    print(df.head(10))

    getWordCloud(words)

elif info == 2:

    comments = []

    words=[]

    for i in range(0, 60, 20):

        url = "https://book.douban.com/subject/10517238/comments/?start={}&limit=20&status=P&sort=time".format(

            i)  # 前3页短评信息(最新)

        getComments(url)

    df = pd.DataFrame(comments, columns=title)

    print(df.head(10))

    print("点赞数前10位的短评信息:")

    df = df.sort_values(by='点赞数', ascending=False)

    print(df.head(10))

    getWordCloud(words)


image.png

标签:comment,10,2024.5,短评,30,regex,words,line
From: https://www.cnblogs.com/luoqingci/p/18246064

相关文章

  • 2024.5.29
    8-1【Python0025】中国大学排名数据分析与可视化分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取:(1)按照排名......
  • 2024.5.31
    8-3【Python0027】函数图形绘制分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】设,,,其中,完成下列操作:(1)在同一坐标系下用不同的颜色和线型绘制y1、y2和y3三条曲线;(2)在同一绘图框内以子图形式绘制y1、y2和y3三条曲线。【练习要求】......
  • 2024.5.11
    8-3【Python0004】验证6174猜想分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】1955年,卡普耶卡(D.R.Kaprekar)对4位数字进行了研究,发现一个规律:对任意各位数字不相同的4位数,使用各位数字能组成的最大数减去能组成的最小数,对得......
  • 2024.5.13
    8-5【Python0006】爬楼梯分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】假设一段楼梯共n(n>1)个台阶,小朋友一步最多能上3个台阶,那么小朋友上这段楼梯一共有多少种方法。【练习要求】请给出源代码程序和运行测试结果,源代码程......
  • 2024.5.15
    8-7【Python0008】筛法求素数分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】用户输入整数n和m(1<n<m<1000),应用筛法求[n,m]范围内的所有素数。【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。【输入......
  • 2024.5.14
    8-6【Python0007】杨辉三角形分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】输出n(0<n)行杨辉三角形,n由用户输入。【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。【输入格式】一行中输入1个整数n。【输......
  • 2024.5.17
    8-9【Python0010】正整数的因子展开式分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】编写程序,输出一个给定正整数x(x>1)的质因子展开式。【输入格式】请在一行中输入整数x的值。【输出格式】对每一组输入的x,按以下格式输出x的质因子......
  • 2024.5.16
    8-8【Python0009】查找鞍点分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】对于给定5X5的整数矩阵,设计算法查找出所有的鞍点的信息(包括鞍点的值和行、列坐标,坐标从1开始)。提示:鞍点的特点:列上最小,行上最大。【练习要求】请给出源代......
  • 2024.5.18
    8-10【Python0011】牛顿迭代法分数10全屏浏览作者 doublebest单位 石家庄铁道大学【题目描述】编写程序,使用牛顿迭代法求方程在x附近的一个实根。【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。【输入格式】请在一行......
  • 2024.5.19
    8-11【Python0012】对比Python中的列表、元组、字典、集合、字符串等之间异同分数10全屏浏览作者 doublebest单位 石家庄铁道大学针对Python中的列表、元组、字典、集合、字符串,查阅资料,请以条目形式从各方面对比它们之间的异同。要求结合代码......