2014-09-12 4 views
-2

다음 코드는 라인에 print (aTweet + '~' + timeSource[x] + '~' + keyWord[i]) 오류를 계속 제공합니다. 이것은 keyword[i] 용어와 관련이 있습니까? 나는 보통 Index out of range이 목록 요소가 존재하지 않는 색인을 제공한다는 것을 이해합니다. 그 오류를 뜻이 절에서 거짓말을 사실 수 있습니다Python : 인덱스 범위 초과 오류

if (len(splitSource) > 20): 
       max_range = 19 
      else: 
       max_range = len(splitSource) 

참조 코드 :

import re 
from re import sub 
import time 
import cookielib 
from cookielib import CookieJar 
import urllib2 
from urllib2 import urlopen 
import difflib 
import sys 

cj = CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
opener.addheaders = [('User-agent', 'Mozilla/5.0')] 

keyWord = ["Scotch"] 

def main(): 
    i=0 
    while i<len(keyWord): 
     startingLink = 'https://twitter.com/search/realtime?q='+keyWord[i] 
     tUrl = startingLink+'&src=hash' 

     oldTwit = [] 
     newTwit = [] 


     howSimAr = [.5,.5,.5,.5,.5] 

     sourceCode = opener.open(tUrl).read() 
     splitSource = re.findall(r'<p class="js-tweet-text tweet-text">(.*?)</p>',sourceCode) 
     timeSource = re.findall(r'js-nav" title="(.*?)"',sourceCode) 

     if (len(splitSource) > 20): 
      max_range = 19 
     else: 
      max_range = len(splitSource) 

     print '' 
     print '' 
     print '' 
     ##print 'Keyword: ' + keyWord[i] 
     print ''    

     for x in range (0, max_range): 
      aTweet = re.sub(r'<.*?>','',splitSource[x]) 
      print (aTweet + '~' + timeSource[x] + '~' + keyWord[i]) 
      #print ';' 
      newTwit.append(aTweet) 

##  comparison = difflib.SequenceMatcher(None, newTwit, oldTwit) 
##  howSim = comparison.ratio() 
##  print ';' 
##  print 'This selection is',howSim,'similar to the past' 
##  howSimAr.append(howSim) 
##  howSimAr.remove(howSimAr[0]) 
## 
##  waitMultiplier = reduce(lambda x, y: x+y, howSimAr)/len(howSimAr) 
## 
##  print '' 
##  print 'The current similarity array:',howSimAr 
##  print 'Our current Multiplier:', waitMultiplier 

     oldTwit = [None] 
     for eachItem in newTwit: 
      oldTwit.append(eachItem) 

     newTwit = [None] 

     time.sleep(2) 
     x = 0 
     i = i + 1 

## except Exception, e: 
##  print str(e) 
##  print 'errored in the main try' 
main() 
+0

'timeSource'에'x '를 사용하여 색인을 생성하고 있지만'x'의 범위는'splitSource'의 길이에 의해 결정됩니다 ('max_range '를 통해). 'splitSource'가'timeSource'보다 길고 (더 많은 요소를 가졌을 때) 작동하지 않습니다. –

+0

@Tom 다른 변수를 만드는 것이 더 낫겠습니까? –

+0

'splitSource'와'timeSource's 사이의 관계가 무엇인지, 또는 여러분의 코드가 무엇을하려고하는지 명확하지 않습니다. 둘 다 트윗과 관련이있는 것으로 보이지만 어떤 데이터를 기대하는지 모르겠습니다. 예 : "Scotch"라는 키워드를 검색 할 때,'splitSource'에서 얼마나 많은 아이템을 기대하고'timeSource'에서 얼마나 많은 아이템을 기대합니까? –

답변

0

을 트위터 검색 페이지의 소스 코드에 js-nav" title=" 그래서 두 번째 정규 표현식의 제로 발생을 것이다 아무것도 찾지 마라. 사실, 보여줄 것이다

for x in range (0, max_range): 

전에

print "len(timeSource) =", len(timeSource) 
print "max_range =", max_range 

를 추가 :

당신이 archieve 원하는 무엇이든
len(timeSource) = 0 
max_range = 20 

, 사용 좋을 것 HTMLParser 정도 HTML로 작업하려면 re을 사용하는 것보다 이렇게하면 timeSource[x]splitSource[x]이 모두 x에 대해 서로 속하게되는지 쉽게 알 수 있습니다.

관련 문제