怎么将上段代码按评分分类
时间: 2024-03-30 08:40:45 浏览: 10
将上段代码按评分分类的方法如下:
1. 首先在DataFrame中添加一个列"评分分类",用于存储电影的评分分类。
2. 在for循环中获取每个电影的评分,并根据评分将电影分到相应的分类中。可以使用if-elif语句或者pandas的cut函数进行分类。
3. 将每个电影的评分分类存到"评分分类"列中。
4. 最后可以使用pandas的groupby函数对DataFrame进行按评分分类的统计。
修改后的代码如下:
```
import requests
from lxml import etree
import pandas as pd
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46'
}
def get_first_text(list):
try:
return list[0].strip()
except:
return ""
df=pd.DataFrame(columns=["序号","标题","链接","导演","评分","评价人数","简介","评分分类"]) # 添加“评分分类”列
urls = ['https://movie.douban.com/top250?start={}&filter='.format(str(i * 25)) for i in range(10)]
count = 1
for url in urls:
res = requests.get(url=url, headers=headers)
html = etree.HTML(res.text)
lis = html.xpath('//*[@id="content"]/div/div[1]/ol/li')
for li in lis:
title = get_first_text(li.xpath('./div/div[2]/div[1]/a/span[1]/text()'))
src = get_first_text(li.xpath('./div/div[2]/div[1]/a/@href'))
dictor = get_first_text(li.xpath('./div/div[2]/div[2]/p[1]/text()'))
score = float(get_first_text(li.xpath('./div/div[2]/div[2]/div/span[2]/text()'))) # 将评分转为浮点数
comment = get_first_text(li.xpath('./div/div[2]/div[2]/div/span[4]/text()'))
summary = get_first_text(li.xpath('./div/div[2]/div[2]/p[2]/span/text()'))
# 根据评分分类
if score >= 9.0:
score_class = "优秀"
elif score >= 8.0:
score_class = "良好"
elif score >= 7.0:
score_class = "一般"
else:
score_class = "较差"
df.loc[len(df.index)]=[count,title,src,dictor,score,comment,summary,score_class] # 将评分分类存到DataFrame中
count += 1
# 按评分分类统计
df.groupby("评分分类").agg({"评分":["count","mean","max","min"]})
```
运行后,可以得到按评分分类的统计结果。其中,count表示数量,mean表示平均值,max表示最大值,min表示最小值。