-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()
'timeSource'에'x '를 사용하여 색인을 생성하고 있지만'x'의 범위는'splitSource'의 길이에 의해 결정됩니다 ('max_range '를 통해). 'splitSource'가'timeSource'보다 길고 (더 많은 요소를 가졌을 때) 작동하지 않습니다. –
@Tom 다른 변수를 만드는 것이 더 낫겠습니까? –
'splitSource'와'timeSource's 사이의 관계가 무엇인지, 또는 여러분의 코드가 무엇을하려고하는지 명확하지 않습니다. 둘 다 트윗과 관련이있는 것으로 보이지만 어떤 데이터를 기대하는지 모르겠습니다. 예 : "Scotch"라는 키워드를 검색 할 때,'splitSource'에서 얼마나 많은 아이템을 기대하고'timeSource'에서 얼마나 많은 아이템을 기대합니까? –