#!/usr/bin/env python import re, urllib r_json = re.compile(r'^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]+$') r_string = re.compile(r'"(\\.|[^"\\])*"') def json(text): """Evaluate JSON text safely (we hope).""" if r_json.match(r_string.sub('', text)): return eval(text, {'__builtins__': None}, {}) print text raise ValueError('Input must be serialised JSON.') def sparql(query): service = 'http://www.sparql.org/sparql' qstring = 'query=%s&default-graph-uri=&stylesheet=&output=json' uri = service + '?' + (qstring % urllib.quote(query)) u = urllib.urlopen(uri) bytes = u.read() u.close() return json(bytes) query = """\ PREFIX : SELECT ?time ?cloud ?temperature ?precipitation FROM WHERE { [ :time ?time; :cloudCover [ :percent ?cloud ]; :temperature [ :celsius ?temperature ]; :precipitation [ :inches ?precipitation ] ] } """ def convert(place): results = sparql(query % place) data = [] for bindings in results['results']['bindings']: w3cdtf = bindings['time']['value'] cloudCover = bindings['cloud']['value'] temperature = bindings['temperature']['value'] precipitation = bindings['precipitation']['value'] data.append((w3cdtf, cloudCover, temperature, precipitation)) f = open('%s.forecast.txt' % place, 'w') for (w3cdtf, cloudCover, temperature, precipitation) in sorted(data): print >> f, w3cdtf, temperature, cloudCover, precipitation f.close() def main(argv=None): if argv is None: argv = __import__('sys').argv if len(argv) == 2: place = argv[1] convert(place) else: Exception('usage: %prog ') if __name__ == '__main__': main()