【问题标题】:Function won't loop函数不会循环
【发布时间】:2015-05-12 12:35:28
【问题描述】:

我已经编写了一段代码,它可以很好地打印,但是当我创建它的函数并尝试返回它时失败了。这是原始代码:

import requests
from bs4 import BeautifulSoup
import wikipedia

source_code = requests.get('http://en.wikipedia.org/wiki/IBM')
plain_text = source_code.text
plain_text = plain_text[:plain_text.find('id="toc"')]
soup = BeautifulSoup(plain_text)

for div in soup.findAll('a'):
    if div.parent.name == 'p':
        href = div.get('href')
        href = href.replace(',', '')
        href = href.replace('-', ' ')
        href = href.replace('(', '')
        href = href.replace(')', '')
        href = href.replace('_', ' ')

        print (href[6:])
        href = href.replace(' ', '_')
        href = href.replace(' ^ ', '')
        try:
            print(wikipedia.summary(href[6:]))
        except wikipedia.exceptions.DisambiguationError as e:
            print (e.options)

它格式化文本并给我一个维基百科页面的标题和摘要以及原始摘要中链接的所有摘要,这正是我想要的。不幸的是,这需要成为更大程序的一部分,因此我制作了一个函数(也许我应该以另一种方式来做?) 它看起来像这样:

import requests
from bs4 import BeautifulSoup
import wikipedia

source_code = requests.get('http://en.wikipedia.org/wiki/IBM')
plain_text = source_code.text
plain_text = plain_text[:plain_text.find('id="toc"')]
soup = BeautifulSoup(plain_text)

def ELS():
    for div in soup.findAll('a'):
        if div.parent.name == 'p':
            href = div.get('href')
            href = href.replace(',', '')
            href = href.replace('-', ' ')
            href = href.replace('(', '')
            href = href.replace(')', '')
            href = href.replace('_', ' ')

            return href[6:]
            href = href.replace(' ', '_')
            href = href.replace(' ^ ', '')
            try:
                return wikipedia.summary(href[6:])
            except wikipedia.exceptions.DisambiguationError as e:
                return e.options

print (ELS())

但由于某种原因,它不会循环,只是打印第一个标题然后中断,也许这是一个简单的问题,只是我错过了一些东西

【问题讨论】:

  • 当你使用return时,函数立即返回,所以循环结束。
  • 不要在循环内返回,将值连接到结果字符串上。循环完成后返回该字符串。
  • 好吧,我想可能是这样的,谢谢:)
  • @SamuelHåkansson 连接速度很慢。您应该收集列表中的所有子字符串并使用join 方法构建最终字符串,或者通过将return 替换为'yield' 将您的函数转换为生成器。由于多功能性,后者可以说是更可取的。

标签: python loops return function


【解决方案1】:

您只需将 print 替换为 return,您的函数行为现在就有问题了,因为函数在调用 return 命令时结束了它的执行。

试试这样的:

def ELS():
    output = []
    for div in soup.findAll('a'):
        if div.parent.name == 'p':
            href = div.get('href')
            href = href.replace(',', '')
            href = href.replace('-', ' ')
            href = href.replace('(', '')
            href = href.replace(')', '')
            href = href.replace('_', ' ')

            output.append(href[6:])
            href = href.replace(' ', '_')
            href = href.replace(' ^ ', '')
            try:
                output.append(wikipedia.summary(href[6:]))
            except wikipedia.exceptions.DisambiguationError as e:
                output.append(e.options)

    return "\n".join(output)

【讨论】:

    【解决方案2】:

    return 立即退出函数。

    收集列表中的信息并返回:

    def ELS():
        results = []
        for div in soup.findAll('a'):
            if div.parent.name == 'p':
                href = div.get('href')
                href = href.replace(',', '')
                href = href.replace('-', ' ')
                href = href.replace('(', '')
                href = href.replace(')', '')
                href = href.replace('_', ' ')
    
                href = href.replace(' ', '_')
                href = href.replace(' ^ ', '')
                try:
                    results.append((href[6:], wikipedia.summary(href[6:])))
                except wikipedia.exceptions.DisambiguationError as e:
                    results.append((href[6:], e.options))
        return results
    

    然后您可以循环遍历结果;每个条目都是一个具有处理后的href 值和wikipedia.summary() 输出或异常e.options 属性的元组。然后,您可以在其他代码中进一步重用此信息。

    【讨论】:

    • 我试过了:summaryList = [] (code) try: summaryList.append(wikipedia.summary(href[6:])) except wikipedia.exceptions.DisambiguationError as e: summaryList.append (e.options) 返回摘要列表
    • 不确定这是否是故意的,但行为与 OP 的代码略有不同,因为您在最后两个替换之后附加了 href[6:]
    • 我尝试过添加或更改:summaryList=[] try: summaryList.append(wikipedia.summary(href[6:])) except wikipedia.exceptions.DisambiguationError as e: summaryList.append (e.options) 返回 summaryList 错误: File..worder.py",第 102 行,在 WTD() File..worder.py",第 69 行,在 WTD textFile.write(repr(ELS()) + '\n') File..\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u03c4 ' 在位置 11342:字符映射到
    • @zehnpaard 对,这不是故意的;将其存储在新变量中是一种选择。
    • @SamuelHåkansson 打开文件时需要使用显式编码; CP1252(西方字符的 Windows 代码页)的默认编码无法处理 Wikipedia 可以在标题中生成的所有内容。
    【解决方案3】:

    你正在退出你的函数,因此打破了循环。您需要将搜索结果添加到列表或字典中,并在循环后返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多