首页 > 其他分享 >4.24

4.24

时间:2024-06-19 18:14:47浏览次数:12  
标签:comment 10 短评 regex words line 4.24

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)

标签:comment,10,短评,regex,words,line,4.24
From: https://www.cnblogs.com/szm123/p/18256961

相关文章

  • 4.24博客
    python学习importmathclassShape:defcal_perimeter(self):    pass defcal_area(self):    pass defcal_volume(self):    passclassPoint(Shape):def\__init_\_(self,x=0,y=0):    self.x=x    self.y=y defsetX(s......
  • 4.24
    publicstaticStringshortest(Useruser){Connectionconnection=JDBCUtils.getConn();StringstartingStation=user.getStarting_Station();StringterminusStation=user.getTerminus_Station();//1.构建站点名称到ID的映射Map<String,Integer>......
  • 4.24团队开发第5天
    学习时间2h代码行数155行博客量1篇学习内容对个人页面进行了制作<template><viewclass="my"><cu-custombgColor="bg-black":isBack="false"><blockslot="backText">返回</block>......
  • 2024.4.24
    /*==================初始化====================*/body{ background-color:#f1f1f1; font-size:28upx; color:#333333; font-family:HelveticaNeue,Helvetica,sans-serif;}view,scroll-view,swiper,button,input,textarea,label,navigator,image{ box-sizi......
  • 腾讯公益赛个人冲刺博客2(2024.4.24)
    登录注册页面,问题暂无,明天做帮扶的第一个界面<?xmlversion="1.0"encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.andro......
  • 腾讯公益赛冲刺团队博客2(2024.4.24)
    未完成sos、帮扶、社交、在线医生四个功能进行中百度地图权限申请和登录注册后的主界面已完成登录注册基本内容 ......
  • 4.24
    已经往数据库插入图片了,现在可以去除图片了,这里我用的是游标package你的包名;importandroidx.appcompat.app.AppCompatActivity;importandroid.content.Intent;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlit......
  • 4.24
    今天完成了快递代取部分的全部接口文档,因为快递和购餐方面类似,所以做完一个其实就是全部做完了,对于数据库表中设计餐食保存的元素为json格式我想了想可以在前端中优化成一个字符串,这样既可以省时间也可以避免不必要的错误,这方面我需要跟我的前端逻辑实现的队友商量一下,商量下是否......
  • 2024.04.24 完成的任务
    今天在菜鸟教程学了这些内容。。。具体内容如下:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>我的联通</title><head></head></head><body><......
  • 4.24
    今天Miqa闲来无事对教授说:“你是原。”教授说:“我不是原。”经过了很长时间的激烈的辩论之后事情发展到了这样:Miqa:“你不能证明你不是原,所以你是原。”教授:“你也不能证明,你也是原。”Miqa沉思片刻Miqa:“我能证明我不是原。”证明过程:由基本事实得,咱俩当中有且仅有一......