【问题标题】:Python: How to access the elements in a generator object and put them in a Pandas dataframe or in a dictionary?Python:如何访问生成器对象中的元素并将它们放入 Pandas 数据框或字典中?
【发布时间】:2019-12-01 16:47:57
【问题描述】:

我在 python 中使用scholarly 模块来搜索关键字。我正在返回一个生成器对象,如下所示:

import pandas as pd
import numpy as np
import scholarly

search_query = scholarly.search_keyword('Python')
print(next(search_query))

{'_filled': False,
 'affiliation': 'Juelich Center for Neutron Science',
 'citedby': 75900,
 'email': '@fz-juelich.de',
 'id': 'zWxqzzAAAAAJ',
 'interests': ['Physics', 'C++', 'Python'],
 'name': 'Gennady Pospelov',
 'url_picture': 'https://scholar.google.com/citations?view_op=medium_photo&user=zWxqzzAAAAAJ'}

我想访问 'citedby' 元素,但是当我尝试执行 next(search_query)['citedby'] 时,它返回 TypeError: 'Author' object is not subscriptable

我的问题是如何访问生成器对象中的元素?以及如何将该对象转换为 Pandas 数据框?

【问题讨论】:

    标签: python generator google-scholar


    【解决方案1】:

    这不是生成器问题。生成器生成的对象不是字典

    诚然,scholary 库通过为您提供类似字典的字符串转换的 Author 实例并没有实际记录该类 支持的 API 来帮助解决问题。

    Author 表示中的每个“键”实际上是对象上的一个 属性

    author = next(search_query)
    print(author.citedby)
    

    可以使用vars() function获取对象的字典:

    author_dict = vars(author)
    

    不过,数据不一定直接映射到数据框。例如,interests 列表如何在数据框表格数据结构中表示?而且您也不想包含_filled 内部属性(如果author.fill() 已被调用,这是一个要记录的标志)。

    也就是说,您可以通过将生成器映射到 vars 函数来从字典中创建一个数据框:

    search_query = scholarly.search_keyword('Python')
    df = pd.DataFrame(map(vars, search_query))
    

    然后在必要时删除 _filled 列,并将 interests 列转换为更结构化的内容,例如具有 0 / 1 值或类似值的单独列。

    请注意,这将是缓慢,因为scholarly 库按顺序浏览 Google 搜索结果,并且库故意延迟请求并随机休眠每次间隔 5-10 秒,以避免 Google 阻止请求。因此,您必须耐心等待,因为Python 关键字搜索很容易产生近 30 页的结果。

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 2023-03-28
      • 2023-03-22
      • 1970-01-01
      • 2011-10-06
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      相关资源
      最近更新 更多