ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python-中国大学排名数据分析与可视化

2022-05-13 00:03:28  阅读:323  来源: 互联网

标签:count plt python rank 可视化 year print 中国大学 select


【题目描述】以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取:

(1)按照排名先后顺序输出不同年份的前10位大学信息,并要求对输出结果的排版进行优化;

(2)结合matplotlib库,对2015-2019年间前10位大学的排名信息进行可视化展示。

(3附加)编写一个查询程序,根据从键盘输入的大学名称和年份,输出该大学相应的排名信息。如果所爬取的数据中不包含该大学或该年份信息,则输出相应的提示信息,并让用户选择重新输入还是结束查询;

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

源代码:

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
from matplotlib import pyplot as plt


def get_rank(url):
    count = 0
    rank = []
    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.3"
    }
    resp = requests.get(url, headers=headers).content.decode()
    soup = bs(resp, "lxml")
    univname = soup.find_all('a', class_="name-cn")
    for i in univname:
        if count != 10:
            university = i.text.replace(" ", "")
            score = soup.select("#content-box > div.rk-table-box > table > tbody > tr:nth-child({}) > td:nth-child(5)"
                                .format(count + 1))[0].text.strip()
            rank.append([university, score])
        else:
            break
        count += 1
    return rank


total = []
u_year = 2015
for i in range(15, 20):
    url = "https://www.shanghairanking.cn/rankings/bcur/20{}11".format(i)
    print(url)
    title = ['学校名称', '总分']
    df = pd.DataFrame(get_rank(url), columns=title)
    total.append(df)
for i in total:
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    x = list(i["学校名称"])[::-1]
    y = list(i["总分"])[::-1]
    # 1.创建画布
    plt.figure(figsize=(20, 8), dpi=100)
    # 2.绘制图像
    plt.plot(x, y, label="大学排名")
    # 2.2 添加网格显示
    plt.grid(True, linestyle="--", alpha=0.5)
    # 2.3 添加描述信息
    plt.xlabel("大学名称")
    plt.ylabel("总分")
    plt.title(str(u_year) + "年软科中国最好大学排名Top10", fontsize=20)
    # 2.5 添加图例
    plt.legend(loc="best")
    # 3.图像显示
    plt.savefig(str(u_year)+".png")
    plt.show()

    u_year += 1

while True:
    info = input("请输入要查询的大学名称和年份:")
    count = 0
    university, year = info.split()
    year = int(year)
    judge = 2019 - year
    tmp = total[::-1]
    if 4 >= judge >= 0:
        name = list(total[judge - 1]["学校名称"])
        for j in name:
            if university == j:
                print(university + "在{0}年排名第{1}".format(year, count + 1))
                break
            count += 1
        if count ==10:
            print("很抱歉,没有该学校的排名记录!!!")
            print("请选择以下选项:")
            print("   1.继续查询")
            print("   2.结束查询")
            select = int(input(""))

            if select == 1:
                continue
            elif select == 2:
                break
        else:
            break
    else:
        print("很抱歉,没有该年份的排名记录!!!")
        print("请选择以下选项:")
        print("   1.继续查询")
        print("   2.结束查询")
        select = int(input(""))

        if select == 1:
            continue
        elif select == 2:
            break

运行结果:

 

 

 

 

 

 

标签:count,plt,python,rank,可视化,year,print,中国大学,select
来源: https://www.cnblogs.com/yuxuan-light-of-Taihu-Lake/p/16265029.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有