2017-03-17 2 views
0

파이썬 스크립트에 어떤 문제가 있습니까?정의 된 함수는 python2.7에서 for 루프로 사용됩니다.

from BeautifulSoup import BeautifulSoup 
import requests 
import re 
from collections import defaultdict 
import itertools 
import pandas as pd 

def wego(weburl,annot): 
    print 'Go Term: ', weburl.split('=')[-1] 
    html=requests.get(weburl).text 
    soup=BeautifulSoup(html) 
    desc=r"desc=\".*\"" 
    print "GO leave 2 term:",(re.findall(desc,str(soup))[0].split('"')[1]) 
    pattern=r"Unigene.*A" 
    idDF = pd.DataFrame(columns=['GeneID']) #creates a new datafram 
    idDF['GeneID'] = pd.Series(re.findall(pattern,str(soup))).unique() 
    print "Total Go term is :",idDF.shape[0] 
    old=pd.read_csv(annot,usecols=[0,7,8]) 
    getset=pd.merge(left=idDF,right=old,left_on=idDF.columns[0],\ 
    right_on=old.columns[0]) 
    updown=getset.groupby(getset.columns[1]).count() 
    print updown 
    print "Max P-value: ","{:.3e}".format(getset['P-value'].max()) 

with open("gourl.txt") as ur: 
    d=[] 
    for url in ur: 
    we=wego(url,annot="file.csv") 
    d.append(we) 

gourl.txt 파일은 내 질문에 스크립트가 성공할 수있는 이유 중 하나

http://stackoverflow.com/questions=1 
http://stackoverflow.com/questions=2 

에 의해 일부 URL을 한 줄 때 gourl.txt 파일에 하나 개의 URL을 때 실패 하나 이상?

오류는 다음과 같습니다 당신이 우리에게 준 스택 추적을 보면

IndexError: list index out of range 
IndexErrorTraceback (most recent call last) 
<ipython-input-79-a852fe95d69c> in <module>() 
    2  d=[] 
    3  for url in ur: 
----> 4   we=wego(url,annot="file.csv") 
    5   d.append(we) 
<ipython-input-4-9fdf25e75434> in wego(weburl, annot) 
    5  soup=BeautifulSoup(html) 
    6  desc=r"desc=\".*\"" 
----> 7  print "GO leave 2 term:",(re.findall(desc,str(soup)) 
[0].split('"')[1]) 
    8  pattern=r"Unigene.*A" 
    9  idDF = pd.DataFrame(columns=['GeneID']) #creates a new dataframe 
IndexError: list index out of range 
+0

'requests.get()'에 전달되는'weburl'을 확인 했습니까? 확인해야 할 또 다른 것은'requests.get()'응답 객체의 상태 코드입니다. – heyiamt

+0

당신의 코드를 실행하려고 시도하고'IndentationError : 28 번 줄에 들여 쓰기 된 블록이 예상됩니다. '당신이 실행중인 정확한 코드라고 확신합니까? – Kevin

+0

@Kevin 예, 성공적으로 실행했습니다. '거래 = (url, annoy = "file.csv")'코드는 문제가되지 않습니다. – hope

답변

0

당신이 답을 볼 수 있습니다. 마지막 줄은 당신이 당신은이 목록이 줄에 액세스 할

print "GO leave 2 term:",(re.findall(desc,str(soup))[0].split('"')[1]) 

에서 ('범위를 벗어난') 존재하지 않는 목록 요소에 액세스하려고하는 것을 말한다. 하나는 첫 번째 일치 패턴을 얻고 다른 하나는 split('"')에 의해 생성 된 두 번째 용어를 얻습니다.

아마도 두 번째 URL에는 예상되는 패턴이 없을 것입니다. 질문이 솔루션을

matches = re.findall(desc, str(soup)) 
tokens = [] 
if matches: 
    tokens = matches[0].split('"') 
if len(tokens) > 1: 
    print("GO leave 2 term:", tokens[1]) 
+0

감사! 당신의 제안에 따라 스크립트를 수정할 수 있습니다. 그러나 최종 URL은 gourl.txt 파일에 둘 이상의 URL이있을 때만 결과를 얻을 수 있습니다. – hope

+0

스크립트를 실행하려는 모든 URL에 대해 사용자가 예상 할 것으로 예상되는 내용을 확인하십시오. 어쩌면 regexes에서 다른 패턴을 사용해야합니다. 추가 도움이 필요하면이 스크립트가 작동하지 않는 샘플 입력을 추가해야합니다. –

+0

google 드라이브에서 구문 분석하려는 URL에 대한 두 개의 html 파일을 저장했습니다 ([link] (https://drive.google .com/open? id = 0B4N58_pNXx8hRk1SeHNvS0FjY2M) 및 [link] (https://drive.google.com/open?id=0B4N58_pNXx8hbDZ0MkZ2eVNYRUk)). 그리고이 파이썬 스크립트를 실행할 때이 파일 ([link] (https://docs.google.com/document/d/1TMps1PmpMvxKFV2cdtdU8JD762_BtHC43UOAccsj9jY/edit?usp=sharing))은 내 결과물이며 질문입니다. – hope

0

그래서 행복 것을 :

는이 같은 것을 사용할 수 있습니다. 문제는 \ gourl.txt 파일을 읽을 때 발생합니다. 다음과 같이 표시됩니다 :

>>> with open("wegourl.txt") as ur: 
...  d=[] 
...  for url in ur: 
...   print url 
...   

http://stackoverflow.com/questions=1 

http://stackoverflow.com/questions=2 

의심 할 여지없이, 줄 바꿈으로 인한 빈 줄은 잘못된 URL이 아니며이 스크립트를 방해합니다. 파일을 읽을 때 \ n을 지울 수 있습니다 : url=url.strip('\n')