Skip to content

Instantly share code, notes, and snippets.

@ebraminio
Created February 16, 2016 22:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebraminio/52ce97be288a669ea541 to your computer and use it in GitHub Desktop.
Save ebraminio/52ce97be288a669ea541 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python3
# python3 script to retrieve Iran and Afghnistan provinces' capital cities coordinates.
# Written by Ebrahim Byagowi
import json
import re
import requests
query_result = requests.get('https://query.wikidata.org/sparql', {
"query": """
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX p: <http://www.wikidata.org/prop/>
PREFIX q: <http://www.wikidata.org/prop/qualifier/>
PREFIX v: <http://www.wikidata.org/prop/statement/>
SELECT DISTINCT ?en ?fa ?countryEn ?coord
WHERE {
{ ?province wdt:P31* wd:Q1344695 } UNION # find Iran provinces (Q1344695)
{ ?province wdt:P31* wd:Q158683 } . # and Afghanistan provinces (Q158683)
?province wdt:P17 ?country . # put country (P17) of province on ?country
?province wdt:P36 ?capital . # put province capital (P36) value on ?capitalCity
?capital wdt:P625 ?coord . # put coordinate (P625) of province capital on ?coord
SERVICE wikibase:label {
bd:serviceParam wikibase:language "fa" .
?capital rdfs:label ?fa
}
SERVICE wikibase:label {
bd:serviceParam wikibase:language "en" .
?capital rdfs:label ?en .
?country rdfs:label ?countryEn
}
}
""",
"format": "json"
}).json()["results"]['bindings']
result = {
"zz": {
"en": "",
"fa": "",
"cities": {
"CUSTOM": {
"en": "None",
"fa": "هیچ کدام",
"latitude": 0,
"longitude": 0
}
}
},
"ir": {
"en": "Iran",
"fa": "ایران",
"cities": {}
},
"af": {
"en": "Afghanistan",
"fa": "افغانستان",
"cities": {}
}
}
for x in query_result:
coord = re.findall(r'\(([\d\.]{,5})\d* ([\d\.]{,5})', x["coord"]["value"])
country = "ir" if x["countryEn"]["value"] == "Iran" else "af"
key = x["en"]['value'].upper().replace(" ", "_")
result[country]["cities"][key] = {
"en": x["en"]['value'],
"fa": x["fa"]['value'],
"latitude": float(coord[0][0]),
"longitude": float(coord[0][1])
}
with open('cities.json', 'w+') as f:
json.dump(result, f, indent=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment