2013-12-11 43 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