| 1 | #!/usr/bin/env python |
|---|
| 2 | |
|---|
| 3 | # a test for demonstration using Sketch Engine through json interface |
|---|
| 4 | |
|---|
| 5 | import urllib, urllib2, base64 |
|---|
| 6 | import simplejson |
|---|
| 7 | |
|---|
| 8 | usr = '<username>' |
|---|
| 9 | passwd = '<password>' |
|---|
| 10 | |
|---|
| 11 | base_url = 'http://localhost/auth/run.cgi/' |
|---|
| 12 | method = 'view' |
|---|
| 13 | |
|---|
| 14 | # creating query string |
|---|
| 15 | attrs = dict(corpname='bnc', q='', pagesize='1', format='json') |
|---|
| 16 | # query_list can be read from a file, ... |
|---|
| 17 | query_list = ['[lemma="test"]', |
|---|
| 18 | '[lemma="drug"][lemma="test"]', |
|---|
| 19 | '[lemma="blood"][lemma="test"]', |
|---|
| 20 | '[lemma="test"][lemma="result"]' |
|---|
| 21 | ] |
|---|
| 22 | |
|---|
| 23 | for query in query_list: |
|---|
| 24 | attrs['q'] = 'q' + query |
|---|
| 25 | |
|---|
| 26 | encoded_attrs = urllib.quote(simplejson.JSONEncoder().encode(attrs)) |
|---|
| 27 | url = base_url + method + '?json=%s' % encoded_attrs |
|---|
| 28 | |
|---|
| 29 | request = urllib2.Request(url) |
|---|
| 30 | |
|---|
| 31 | # authentication |
|---|
| 32 | base64string = base64.encodestring('%s:%s' % (usr, passwd))[:-1] |
|---|
| 33 | request.add_header("Authorization", "Basic %s" % base64string) |
|---|
| 34 | |
|---|
| 35 | # json data receiving |
|---|
| 36 | file = urllib2.urlopen(request) |
|---|
| 37 | data = file.read() |
|---|
| 38 | file.close() |
|---|
| 39 | |
|---|
| 40 | # now, in the 'data' variable, there is a json string that can be parsed |
|---|
| 41 | # for json syntax (e.g. by simplejson) |
|---|
| 42 | json_obj = simplejson.loads(data) |
|---|
| 43 | |
|---|
| 44 | print query + '\t' + str(json_obj.get('concsize', '0')) |
|---|
| 45 | |
|---|
| 46 | |
|---|