学术前沿趋势分析Task01

文章目录

      • 一、数据集的下载
      • 二、json文件格式以及转换
      • 三、数据预处理
      • 四、数据分析及可视化

# 导入所需的package
import seaborn as sns #用于画图
from bs4 import BeautifulSoup #用于爬取arxiv的数据
import re #用于正则表达式,匹配字符串的模式
import requests #用于网络连接,发送网络请求,使用域名获取对应信息
import json #读取数据,我们的数据为json格式的
import pandas as pd #数据处理,数据分析
import matplotlib.pyplot as plt #画图工具

一、数据集的下载

本次任务中实例的数据集可以在Kaggle上下载,如图所示:

学术前沿趋势分析Task01_第1张图片

(emm~~,这个看似只有906MB的数据,解压下来足足有2.8GB!!奈何自己电脑太**,直接将电脑跑崩了。不过多亏队长大大提供的压缩版数据集!!)可以通过指令:wget https://cdn.coggle.club/arxiv-metadata-oai-2019.json.zip,即可下载这个压缩版的数据集

二、json文件格式以及转换

  • 本次的数据集以json文件格式呈现(全名:JavaScript Object Notation ,是一种轻量级的数据交换格式),其数据集格式如下:

    id:arXiv ID,可用于访问论文;
    submitter:论文提交者;
    authors:论文作者;
    title:论文标题;
    comments:论文页数和图表等其他信息;
    journal-ref:论文发表的期刊的信息;
    doi:数字对象标识符,https://www.doi.org;
    report-no:报告编号;
    categories:论文在 arXiv 系统的所属类别或标签;
    license:文章的许可证;
    abstract:论文摘要;
    versions:论文版本;
    authors_parsed:作者的信息。
    
  • 读入json文件中的数据,并将其转换为dataframe格式:

    data = []
    with open("./arxiv-metadata-oai-2019.json",'r') as f:
        for line in f:
            data.append(json.loads(line))
    
    data = pd.DataFrame(data)
    
    data.head()
    Out[15]: 
              id  ...                                     authors_parsed
    0  0704.0297  ...  [[Yoon, Sung-Chul, ], [Podsiadlowski, Philipp,...
    1  0704.0342  ...                 [[Dugmore, B., ], [Ntumba, PP., ]]
    2  0704.0360  ...         [[Zaqarashvili, T. V., ], [Murawski, K, ]]
    3  0704.0525  ...  [[Aygun, Sezgin, ], [Tarhan, Ismail, ], [Baysa...
    4  0704.0535  ...  [[Pipino, Antonio, ], [Puzia, Thomas H., ], [M...
    [5 rows x 14 columns]
    

    open()和with open()的区别:

    • open():

      1.打开文件:file = open(“文件名”,“读写模式”)

      2.代码段

      3.关闭文件:file.close()

      注意事项:

      使用open方法,文件操作完毕之后必须关闭,否则长期保持对文件的连接状态,造成内存溢出的现象发生。

    • with open():

      1.打开文件:with open (“文件名”,“读写模式”) as file

      2.代码段

      3.关闭文件:自动关闭

      使用with语句优势:

      1.自动关闭文件句柄;

      2.自动显示(处理)文件读取数据异常

三、数据预处理

  1. 粗略统计论文的种类信息:

    data['categories'].describe()
    Out[3]: 
    count     170618     # 元素的个数
    unique     15592     # 元素的种类
    top        cs.CV     # 出现频率最高的元素
    freq        5559     # 出现频率最高的元素的个数
    Name: categories, dtype: object
    

    结果表明:共有170618个数据,有15592个子类(因为有论文的类别是多个,例如一篇paper的类别是CS.AI & CS.MM和一篇paper的类别是CS.AI & CS.OS属于不同的子类别,这里仅仅是粗略统计),其中最多的种类是cs.CV(计算机视觉),共出现了5559次。

  2. 判断本数据集中有多少种独立的数据集

    unique_categories = set([i for l in [x.split(' ') for x in data['categories']] for i in l])
    
    len(unique_categories)
    Out[3]: 172
    

    这里使用了 split 函数将多类别使用 “ ”(空格)分开,组成list,并使用 for 循环font>将独立出现的类别找出来,并使用 set 类别,将重复项去除得到最终所有的独立paper种类

  3. 时间特征进行预处理,获取2019年以后的所有种类论文:

    # 将update_date从例如2019-02-20的str变为datetime格式,并提取year
    data["year"] = pd.to_datetime(data["update_date"]).dt.year
    # 删除update_date特征
    del data["update_date"]
    # 找出year中2019年以后的数据,并将其他数据删除
    # 由于本次使用的数据集就是2019最新的,所以数据没变
    data = data[data["year"] >= 2019]
    data.reset_index(drop=True,inplace=True)
    
    data.head()
    Out[4]: 
              id  ...  year
    0  0704.0297  ...  2019
    1  0704.0342  ...  2019
    2  0704.0360  ...  2019
    3  0704.0525  ...  2019
    4  0704.0535  ...  2019
    [5 rows x 14 columns]
    
  4. 挑选出计算机领域的所有论文:

    在这一步中运用了部分爬虫技术,主要调用了BeautifulSoup包进行爬取;

    并且同样使用了正则操作,关于正则表达式的相关讲解,在我的博客《pandas学习笔记(八)》中有所提及。

    #爬取所有的类别
    website_url = requests.get('https://arxiv.org/category_taxonomy').text #获取网页的文本数据
    soup = BeautifulSoup(website_url,'lxml') #爬取数据,这里使用lxml的解析器,加速
    root = soup.find('div',{
           'id':'category_taxonomy_list'}) #找出 BeautifulSoup 对应的标签入口
    tags = root.find_all(["h2","h3","h4","p"], recursive=True) #读取 tags
    
    level_1_name = ""
    level_2_name = ""
    level_2_code = ""
    level_1_names = []
    level_2_codes = []
    level_2_names = []
    level_3_codes = []
    level_3_names = []
    level_3_notes = []
    
    for t in tags:
        if t.name == "h2":
            level_1_name = t.text
            level_2_code = t.text
            level_2_name = t.text
        elif t.name == "h3":
            raw = t.text
            level_2_code = re.sub(r"(.*)\((.*)\)", r"\2", raw)  # 正则表达式:模式字符串:(.*)\((.*)\);被替换字符串"\2";被处理字符串:raw
            level_2_name = re.sub(r"(.*)\((.*)\)", r"\1", raw)
        elif t.name == "h4":
            raw = t.text
            level_3_code = re.sub(r"(.*) \((.*)\)", r"\1", raw)
            level_3_name = re.sub(r"(.*) \((.*)\)", r"\2", raw)
        elif t.name == "p":
            notes = t.text
            level_1_names.append(level_1_name)
            level_2_names.append(level_2_name)
            level_2_codes.append(level_2_code)
            level_3_names.append(level_3_name)
            level_3_codes.append(level_3_code)
            level_3_notes.append(notes)
    
    df_taxonomy = pd.DataFrame({
           
        'group_name' : level_1_names,
        'archive_name' : level_2_names,
        'archive_id' : level_2_codes,
        'category_name' : level_3_names,
        'categories' : level_3_codes,
        'category_description' : level_3_notes
    })
    
    df_taxonomy.groupby(["group_name","archive_name"])
    
    df_taxonomy.head()
    Out[5]: 
             group_name  ...                               category_description
    0  Computer Science  ...  Covers all areas of AI except Vision, Robotics...
    1  Computer Science  ...  Covers systems organization and hardware archi...
    2  Computer Science  ...  Covers models of computation, complexity class...
    3  Computer Science  ...  Covers applications of computer science to the...
    4  Computer Science  ...  Roughly includes material in ACM Subject Class...
    [5 rows x 6 columns]
    

四、数据分析及可视化

  1. 查看所有大类的paper数量分布:

    _df = data.merge(df_taxonomy, on="categories", how="left").drop_duplicates(["id","group_name"]).groupby("group_name").agg({
           "id":"count"}).sort_values(by="id",ascending=False).reset_index()
    
    _df
    Out[3]: 
                                       group_name     id
    0                                     Physics  38379
    1                                 Mathematics  24495
    2                            Computer Science  18087
    3                                  Statistics   1802
    4  Electrical Engineering and Systems Science   1371
    5                        Quantitative Biology    886
    6                        Quantitative Finance    352
    7                                   Economics    173
    
    
  2. 使用饼图进行结果的可视化

    fig = plt.figure(figsize=(15,12))
    explode = (0, 0, 0, 0.2, 0.3, 0.3, 0.2, 0.1) 
    plt.pie(_df["id"],  labels=_df["group_name"], autopct='%1.2f%%', startangle=160, explode=explode)
    plt.tight_layout()
    plt.show()
    

学术前沿趋势分析Task01_第2张图片

你可能感兴趣的:(python,数据分析,pandas)