2016-12-08 33 views
1

我已經寫了下面的腳本需要包含的代碼都構成對網頁的URL的一部分列表的CSV文件。然後,它打開的每個網頁,掃描它用於PUBMED ID(一個8位的數字),並返回每個PUBMED ID它找到,從已完成的URL以逗號,因此它可以被寫入到一個CSV文件的代碼分隔:從使用Python模塊的功能解析輸出,BeautifulSoup

import csv 
from urllib2 import urlopen 
from bs4 import BeautifulSoup 
import re 

def get_PMID(y): 
     url = 'http://www.ebi.ac.uk/ena/data/view/' + y + '&display=xml' 
     project_page = urlopen(url) 
     soup = BeautifulSoup(project_page, "html.parser") 
     page_text = soup.text 
     PUBMED_TF = bool(re.findall('PUBMED', page_text)) 
     if PUBMED_TF is True: 
      for x in soup.find_all('db', text='PUBMED'): 
       PUBMED = (x.fetchNextSiblings()[0].text) 
       print PUBMED + ',' + y 
     else: 
      return y 

with open('/Users/bj5/Desktop/web_scrape_test.csv','rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     study_accession = row[0] 
     get_PMID(study_accession) 

在這種格式輸出看起來是這樣的,這正是我想要的:

25961941,PRJEB3215 
25909750,PRJEB3215 
26974227,PRJEB3215 
27331909,PRJEB3215 
25038069,PRJEB2705 
25480686,PRJEB2340 

我的問題是,我不希望打印從功能outuput我只是想退貨,所以我可以解析它到另一個函數。但是,當我嘗試通過從函數中刪除打印命令並將其替換爲返回來執行此操作時,我正在丟失部分輸出。請看下圖:

import csv 
from urllib2 import urlopen 
from bs4 import BeautifulSoup 
import re 

def get_PMID(y): 
     url = 'http://www.ebi.ac.uk/ena/data/view/' + y + '&display=xml' 
     project_page = urlopen(url) 
     soup = BeautifulSoup(project_page, "html.parser") 
     page_text = soup.text 
     PUBMED_TF = bool(re.findall('PUBMED', page_text)) 
     if PUBMED_TF is True: 
      for x in soup.find_all('db', text='PUBMED'): 
       PUBMED = (x.fetchNextSiblings()[0].text) 
       return PUBMED + ',' + y 
     else: 
      return y 

with open('/Users/bj5/Desktop/web_scrape_test.csv','rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     study_accession = row[0] 
     print get_PMID(study_accession) 

給出:

25961941,PRJEB3215 
25038069,PRJEB2705 
25480686,PRJEB2340 

我失去了所有,但第一PUBMED ID的每一頁。

誰能告訴我爲什麼,我該如何糾正呢?

回答

0

這是因爲return聲明中斷函數返回值。因此,您正在中斷您的for x in soup.find_all('db', text='PUBMED'):循環,每次調用get_PMID時只返回第一次迭代中獲得的值。

考慮,而不是存儲您的結果爲list並返回最終名單。

def get_PMID(y): 
    # Initialize list of results 
    result = [] 

    url = 'http://www.ebi.ac.uk/ena/data/view/' + y + '&display=xml' 
    project_page = urlopen(url) 
    soup = BeautifulSoup(project_page, "html.parser") 
    page_text = soup.text 
    PUBMED_TF = bool(re.findall('PUBMED', page_text)) 
    if PUBMED_TF is True: 
     for x in soup.find_all('db', text='PUBMED'): 
      PUBMED = (x.fetchNextSiblings()[0].text) 

      # Store each result found 
      result.append(PUBMED + ',' + y) 

     # Loop finished, now is the time to return the list of results 
     return result 
    else: 
     return y 
+0

感謝您的回答,但實際上對我而言並不適合。我猜是因爲return語句仍在循環中,但使用列表絕對是我需要做的事情,我只是將if和else語句的輸出附加到列表中,然後在循環外部返回列表。 –