python数据处理训练

实验内容
(一)、中国大学排名数据分析与可视化;
以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取:

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

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

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

import matplotlib

matplotlib.use('TkAgg')
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}


def get_ranking(year):
    """获取指定年份的前10名大学数据"""
    url = f'https://www.shanghairanking.cn/rankings/bcur/{year}'
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()

        soup = BeautifulSoup(response.content, 'html.parser')
        table = soup.find('table', class_='rk-table')
        if not table:
            print(f"{year}年表格数据不存在")
            return None

        universities = []
        for row in table.select('tbody tr'):
            cols = row.find_all('td')
            if len(cols) < 3:
                continue

            # 提取排名和名称
            rank = cols[0].text.strip()
            name = cols[1].find('a').text.strip() if cols[1].find('a') else cols[1].text.strip()

            universities.append({"排名": rank, "名称": name})

            if len(universities) >= 10:
                break

        return universities

    except requests.exceptions.RequestException as e:
        print(f"{year}年数据获取失败: {str(e)}")
        return None


def visualize_rankings(data, year):
    """使用表格形式可视化排名数据"""
    if not data:
        return

    # 生成表格数据
    table_data = [[d['排名'], d['名称']] for d in data[:10]]

    # 创建更大尺寸的图表对象
    fig, ax = plt.subplots(figsize=(12, 8), dpi=100)  # 增大画布尺寸
    ax.axis('off')

    # 创建表格样式(设置更大字体)
    table = ax.table(
        cellText=table_data,
        colLabels=['  排名  ', '  大学名称  '],  # 增加空格使列宽自然增大
        loc='center',
        cellLoc='center',
        colColours=['#f0f0f0', '#f0f0f0'],
        cellColours=[['#FFFFFF']*2 for _ in range(len(table_data))],
        bbox=[0.1, 0.1, 0.8, 0.8]  # 增大表格相对位置
    )

    # 设置字体和行高
    for key, cell in table.get_celld().items():
        cell.set_height(0.25)  # 增大行高
        if key[0] == 0:  # 表头行
            cell.get_text().set_fontsize(16)
            cell.get_text().set_weight('bold')
        else:
            cell.get_text().set_fontsize(14)

    plt.title(f"{year}年中国大学排名TOP10", fontsize=18, y=1.02)
    plt.tight_layout()

    try:
        plt.show()
    except Exception as e:
        plt.savefig(f'ranking_{year}.png', bbox_inches='tight')
        print(f"可视化结果已保存为 ranking_{year}.png")


def query_ranking():
    """大学排名查询程序"""
    print("\n大学排名查询系统(支持2015-2019年)")
    while True:
        try:
            name = input("\n请输入大学全称(输入'退出'结束):").strip()
            if name.lower() in ['退出', 'exit']:
                break

            year = input("请输入查询年份(2015-2019):").strip()
            if not year.isdigit() or int(year) not in range(2015, 2020):
                print("错误:请输入2015-2019之间的有效年份")
                continue

            # 获取数据
            data = get_ranking(int(year))
            if not data:
                print("当前年份数据暂不可用")
                continue

            # 模糊查询逻辑
            matches = []
            for uni in data:
                # 使用包含匹配(不区分大小写)
                if name.lower() in uni['名称'].lower():
                    matches.append(uni)

            if matches:
                print(f"\n找到{len(matches)}条匹配结果:")
                for uni in matches:
                    print(f"→ {year}年 {uni['名称']} 排名:{uni['排名']}")
            else:
                print(f"\n→ 未找到包含'{name}'的大学")

        except Exception as e:
            print(f"查询出错: {str(e)}")

        print("-" * 40)


if __name__ == "__main__":
    # 任务1:获取并展示历年数据
    for year in range(2015, 2020):
        data = get_ranking(year)
        if data:
            print(f"\n{year}年中国大学排名TOP10:")
            for i, item in enumerate(data[:10], 1):
                print(f"{i:2}. {item['名称']}")
            visualize_rankings(data, year)
        else:
            print(f"{year}年数据获取失败")

    # 启动查询程序
    query_ranking()

【运行测试】

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

(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)

【运行测试】

(三)、函数图形1绘制;
【题目描述】设
图片2.png,图片3.png,图片4.png,其中图片5.png,完成下列操作:

(1)在同一坐标系下用不同的颜色和线型绘制y1、y2和y3三条曲线;

(2)在同一绘图框内以子图形式绘制y1、y2和y3三条曲线。
【源代码程序】
(1)

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.0001)
y1 = x ** 2
y2 = np.cos(x * 2)
y3 = y1 * y2
plt.plot(x, y1,linestyle='-.')
plt.plot(x, y2,linestyle=':')
plt.plot(x, y3,linestyle='--')
plt.savefig("3-1.png")
plt.show()

(2)

【运行测试】

(四)、函数图形2绘制;

【源代码程序】

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2, 2, 0.0001)
y1 = np.sqrt(2 * np.sqrt(x ** 2) - x ** 2)
y2 = (-2.14) * np.sqrt(np.sqrt(2) - np.sqrt(np.abs(x)))
plt.plot(x, y1, 'r', x, y2, 'r')
plt.fill_between(x, y1, y2, facecolor='orange')
plt.savefig("heart.png")
plt.show()

【运行测试】

posted @ 2025-05-22 08:05  茆伟昊  阅读(11)  评论(0)    收藏  举报