2013-12-11 46 views
0

(使用python 3.3.2)嗨,我试图为文本云做一个爬行函数,它将进入链接列表并理想地返回一个列表函数的输出列表中的每个元素。然而,我卡住使用打印功能,打印(二),而不是实际返回我想要的。在我的for循环中,我将如何返回从print(b)语句中获得的所有内容。它可以全部在一个列表中或以某种方式编译。谢谢:) TL;博士:我怎么回所有的东西我从得到循环如何从for循环返回每个值

def crawl(): 
    linkList = inputFunction()[1:][0] #makes a list of a bunch of URL's 
    for i in range(len(linkList)): 
     print(i) 
     t = getHTML(linkList[i]) #getHTML returns tuple of text in the input URL 
     alreadyCrawl = alreadyCrawl + list(linkList[i]) #ignore this 
     t = list(t) 
     b = counting(t) #makes dictionary of word counts 
     print(b) 
    return 
+1

也可以考虑在linkList'使用'用于链路而不是'为i的范围(LEN(链表)):... LINKLIST [I]'。 – Hyperboreus

+0

它通常值得避免像范围内的我(len(linkList)):' - 它可以更清楚地写成:对于i,枚举项(linkList):'(如果你不需要实际上使用'i',作为'linkList:'中的项目)。 – lvc

回答

8

要么你把它们放在一个列表,并在年底返回的列表,或者你"yield"他们(因此创建一个发电机)。

第一种方式:

def f(): 
    acc = [] 
    for x in range(10): 
     acc.append(someFunctionOfX(x)) 
    return acc 

方式二:

def g(): 
    for x in range(10): 
     yield someFunctionOfX(x) 

也许最重要的区别是:如果要someFunctionOfX任何调用导致异常实例1中,该功能将不回报什么。在示例2中,假设第五个值由于某种原因而无法生成,则前四个值已经被放弃并且可能在调用者的上下文中使用。

在这里你可以看到其中的差别:

def f(): 
    acc = [] 
    for x in range(-3, 4): 
     acc.append (2/x) 
    return acc 

def g(): 
    for x in range(-3, 4): 
     yield 2/x 

def testF(): 
    for x in f(): print(x) 

def testG(): 
    for x in g(): print(x) 

调用testF只是失败(ZeroDivisionError:除数为零),并且不显示任何信息。主叫testG打印

-0.6666666666666666 
-1.0 
-2.0 

和失败,那么(ZeroDivisionError:被零除)。


我的(很个人)要么返回一个列表或屈服值标准如下:如果我需要的地方存储的数据,我返回一个列表。如果我只是需要处理每个成员,我会让他们。

0

您可以返回所需的值列表。

def crawl(): 
    list_ret = [] #create empty list to store values 

    for i in range(len(linkList)): 
     # do some stuff 
     b = counting(t) #makes dictionary of word counts 
     list_ret.append(b) #append value to list 
     print(b) 
    return list_ret #return list of values 
0
def crawl(): 
    linkList = inputFunction()[1:][0] #makes a list of a bunch of URL's 
    return_list = [] 
    for i in range(len(linkList)): 
     print(i) 
     t = getHTML(linkList[i]) #getHTML returns tuple of text in the input URL 
     alreadyCrawl = alreadyCrawl + list(linkList[i]) #ignore this 
     t = list(t) 
     b = counting(t) #makes dictionary of word counts 
     return_list.append(b) 
    return return_list