【问题标题】:Python - Tips on Rewrite of BeautifulSoup function to be more elegantPython - BeautifulSoup 函数重写技巧更优雅
【发布时间】:2011-12-16 15:10:53
【问题描述】:

代码正在运行,但我正在寻找有关如何更恰当地编写代码的提示,尤其是 if 的使用。正如你所知道的,我本质上不是程序员......只是一个系统管理员在 python 中做一些摆弄。感谢您提供的任何建议。

def findallWileyLinks():

pagebase = 'http://onlinelibrary.wiley.com'
journallist = 'http://onlinelibrary.wiley.com/browse/publications?type=journal&&start=0&resultsPerPage=3000'

inputList = getinputList()

if inputList:
  alljournallistsoup = BeautifulSoup(getwebpage(journallist))

  if alljournallistsoup:
    alljournallisttags = alljournallistsoup.find('ol', attrs={'id' : 'publications'})

    for eissn in inputList:
      journalatag = alljournallisttags.find('a', attrs={'href' : re.compile(eissn.rstrip() + '$')})

      if journalatag:
        journalsoup = BeautifulSoup(getwebpage(pagebase + journalatag.get('href') + '/issues'))

        if journalsoup:
          allvolumetags = journalsoup.find('ol', attrs={'class' : 'issueVolumes'})
          volumeatags = allvolumetags.findAll('a')

            for volumeatag in volumeatags:
              volumesoup = BeautifulSoup(getwebpage(pagebase + volumeatag.get('href')))

              if volumesoup:
                allissuetags = volumesoup.find('li', attrs={'id' : volumeatag.get('id')[:-5]})
                issueatags = allissuetags.findAll('a')[1:]

                  for issueatag in issueatags:
                    currentlinksavailiable.append(pagebase + issueatag.get('href') + '\n')

      else:
        appendlog('eISSN: ' + eissn.rstrip() + ' not found on alljournallist page.')

    try:
      with open(inputDirectory + selectedPublisher + '_currentlinksavailiable.txt', 'w') as f:
          f.writelines(currentlinksavailiable)

    except IOError as e:
      appendlog('findallLinks() Operation failed probably when creating the new link text file with error: %s' % e.strerror)

【问题讨论】:

    标签: python if-statement beautifulsoup conditional-operator


    【解决方案1】:

    我认为在这里要求重写并不常见。无论如何,这是我的反馈。

    if foo:
        if bar:
            #code
    

    替换为(假设您在 def 内,但您是,对吧?

    if not foo:
        return
    if bar:
        #code
    

    注释应以 hash-blank-uppercase 开头,对已注释掉的代码保留 hash-lowercase。 Peter Norvig 似乎在文本 cmets 中添加了两个破折号。无论如何,你有太多的cmets。代码应该具有足够的描述性。如果一个操作块需要一个描述性的头部,将它移动到一个函数中并使用这个描述作为函数名。这也有助于隔离事物。

    如其他答案所述,请勿使用 if foo 保护您的 for foo 循环。

    inputList = [] 没用,不符合 PEP08,试试input

    【讨论】:

    • if foo and bar 更好——行数越少越好:-)
    • 谢谢,为了便于阅读,我将从我的原始帖子中删除 cmets。我是一名系统管理员,所以编程不一定是我的强项,也不一定是我的强项。
    【解决方案2】:

    很多这样的代码是不必要的。一些例子:

    inputList = []
    inputList = getinputList()
    

    在 Python 中,您无需在将数据分配给变量之前对其进行初始化。第二行本身就可以了。

    if volumeatags:
       for volumeatag in volumeatags:
    

    如果volumeatags为空,则for循环不会执行。

    【讨论】:

      【解决方案3】:

      让我突然想到的一件事是你有很多这样的代码:

      tags = parenttag.findAll('tag')
      
      if tags:
          for tag in tags:
              # do something to tag
      

      您可以保证tags 是此处的列表,因此if tags: 行是多余的。如果在for 循环中使用空列表,则不会执行循环体。

      作为一个小点,可以删除文件开头的inputList = [],因为您会立即用函数调用覆盖它。

      不清楚这是否是更大脚本的一部分,但如果不是,那么如果inputList 为空,您应该终止而不是将脚本的主体包含在if 块中。

      if not inputList:
          sys.exit(1)
      

      而不是

      if inputList:
          # process inputList
      

      您需要将import sys 添加到脚本顶部才能使其正常工作。

      【讨论】:

      • 感谢您的 cmets。 for 之前的 if 已与 inputList = [] 和 currentlinksavailiable = [] 一起被删除。这是更大脚本的一部分。这是为了获取特定发布者的链接而编写的。完善后,我会以它为模板,为其他发布者编写更多类似的功能。
      【解决方案4】:

      您可以将代码放在一个函数中,并使大部分 if 语句为否定语句,并使用 return、continue 或 break 语句。这样可以避免这么多的缩进。

      此外,在 for 循环之前有一个 if 语句,看起来似乎不需要它,因为如果列表为空,则 for 循环将被跳过。 IE。

      if volumeatags:
          for volumeatag in volumeatags:
                  ...
      

      【讨论】:

      • 感谢您关于在 for 之前不需要 if 的评论。这是有道理的,并删除了一些不需要的行。我将阅读有关 return/continue/break 语句的使用,因为我肯定希望尽量减少缩进。再次感谢您。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多