Update: I managed to fix the issue with the help of Jeremy's function that break my data set in to 50 chunks. I have posted the final answer.
I have the following code the reason I want to break the array into chunks is that I am trying to use an api that only allows 50 requests at a time. Also I am java developer who is trying to move to python. What I want to do is break the array into 50 chunks and feed them to the api.
I have a text file that has long list of Ids, I and based on the Id that i read in I am constructing the URL.
import simplejson as json
import sys
import urllib
import traceback, csv, string
# "base" API URL
URL_BASE = 'Some URL'
# set user agent string
urllib.version = "Data Collection Fix it"
page_ids = []
def divide_list(list_, n):
for i in range(0, len(list_), n):
yield list_[i:i + n]
def issue_query():
iFile = open('ReadFromThisFile.txt', "r")
lines = iFile.readlines()
#print len(lines)
for line in lines:
ids = string.split(line)
ids = ids[0]
page_ids.append(ids)
url = URL_BASE
indicies = range(len(page_ids))
File = open("WriteToThisFile.csv", "w")
for indicies in divide_list(page_ids, 50):
count = 0
fiftyIds =[]
url = URL_BASE
for id in indicies:
str(id).strip
url += str(id) + '|'
print url
fiftyIds.append(str(id))
count += 1
print count
rv = urllib.urlopen(url)
j = rv.read().decode("utf-8")
#sys.stderr.write(j + "\n")
data = json.loads(j)
for id in fiftyIds:
try:
s = int(data["query"]["pages"][id]["revisions"][0]["size"])
sys.stderr.write("%d\t%d\n" % (int(id), s))
File.write("%d\t%d\n" % (int(id), s))
#print ("%d\t%d\n" % (int(id), s))
# do something interesting with id and s
except Exception, e:
traceback.print_exc()
File.close()
iFile.close()
issue_query()
I know many experience python developers might give me negative points for asking a simple question like this but I couldn't find any good examples on google or here. So sorry for any trouble if in case I have repeated a question.
Thanks,