【问题标题】:Execute action each Nth appearence of a string字符串每出现第 N 次执行操作
【发布时间】:2018-09-08 07:04:33
【问题描述】:

有一个 python script 允许通过处理带有标识符 (DOI/URL) 列表的文件来进行批量下载。然而,Sci-hub 非常擅长追踪此类行为,因此需要在相当长的时间内进行小批量操作和/或不断更改代理以保持不被发现。

然而,我的想法是这可能是自动化的(根据我几乎不存在的 python 知识,这应该是关键部分)。

      elif args.file:
    with open(args.file, 'r') as f:
        identifiers = f.read().splitlines()
        for identifier in identifiers:
            result = sh.download(identifier, args.output)
            if 'err' in result:
                logger.debug('%s', result['err'])
            else:
                logger.debug('Successfully downloaded file with identifier %s', identifier)

那么有没有可能:

  1. 统计已处理的字符串数
  2. 运行一个循环,每 10 次迭代执行一次特定操作(例如,开始暂停 3-5 分钟)

【问题讨论】:

  • 您可能想先阅读此内容....然后了解这个可怜的人最终发生的事情的故事....非常难过。 wired.com/2011/07/swartz-arrest
  • @octofus:这两个问题的答案可能都是肯定的。但是您需要展示您编写的代码,告诉我们哪些代码不起作用,并让我们从那里提供帮助。不太可能有人会为您编写代码。

标签: python loops download


【解决方案1】:

您可以在 for 循环中放置一个索引。您可以使用模数,或每次重置:

    count = 0
    for identifier in identifiers:
        if count==10:
             action()
             count = 0
        count +=1
        result = sh.download(identifier, args.output)
        if 'err' in result:
            logger.debug('%s', result['err'])
        else:
            logger.debug('Successfully downloaded file with identifier %s', identifier)

如果你只想统计成功的迭代次数,你应该把代码放在else块中:

    count = 0
    for identifier in identifiers:
        result = sh.download(identifier, args.output)
        if 'err' in result:
            logger.debug('%s', result['err'])
        else:
            logger.debug('Successfully downloaded file with identifier %s', identifier)
            if count == 10:
                 action()
                 count = 0
            count +=1

你也可以使用enumerate:

    for count, identifier in enumerate(identifiers):
        if count%10 == 0:
              action()
        result = sh.download(identifier, args.output)
        if 'err' in result:
            logger.debug('%s', result['err'])
        else:
            logger.debug('Successfully downloaded file with identifier %s', identifier)

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2018-03-24
    • 2017-05-09
    • 2022-01-18
    • 2015-11-16
    • 2011-02-04
    • 2011-07-26
    • 2021-04-07
    • 2010-12-25
    相关资源
    最近更新 更多