首页 > 解决方案 > 在谷歌学者中缺少引用的 25 位作者列表中循环

问题描述

我正在使用from scholarly import scholarly从 Google 学者获取教授列表中 25 位教授列表的引用次数。然而,有些作者没有引用。我如何能够循环和停止迭代。我已尝试使用以下代码:

for i in professorlist:
    if i in professorlist:
        a = scholarly.search_author(i)
author = next(search_query)
scholarly.pprint(scholarly.fill(author, sections=['counts']))
if i not in professorlist:
    print ("no citations")

但我得到这个错误:

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-636-b3aa9d644e9f> in <module>
      2     if i in professorlist:
      3         a = scholarly.search_author(i)
----> 4 author = next(search_query)
      5 scholarly.pprint(scholarly.fill(author, sections=['counts']))
      6 if i not in professorlist:

StopIteration:

标签: python

解决方案


当您使用生成器时,您可以获得项目调用next方法,就像您在提供的代码段中所做的那样;但是,如果在耗尽/空的生成器上调用此方法,则会收到 StopIteration 错误。

您可以通过将其包装到这样的 try/except 块中来管理它。

try:
    author = next(search_query)
except StopIteration:
    print("Iterated over all authors")
else:
    # do something with your author
    pass

您还可以使用循环遍历生成器for;它将自动处理 StopIteration 错误,并在生成器耗尽时退出。

for author in search_query:
    # do something with your author
    pass

推荐阅读