Skip to content

Instantly share code, notes, and snippets.

@sweemeng
Last active May 25, 2018 03:27
Show Gist options
  • Save sweemeng/4d034d918eaa4bc4e9c9b0849ab9527f to your computer and use it in GitHub Desktop.
Save sweemeng/4d034d918eaa4bc4e9c9b0849ab9527f to your computer and use it in GitHub Desktop.
Sparql to get size malaysia state #PerlisIsSoSmall
{"Sarawak": 124450, "Kedah": 9427, "Penang": 1031, "Negeri Sembilan": 6686, "Perlis": 821, "Kelantan": 15099, "Selangor": 8104, "Sabah": 76115, "Johor": 19210, "Malacca": 1664, "Terengganu": 12955, "Pahang": 35964, "Perak": 21035}
from SPARQLWrapper import SPARQLWrapper, JSON
from ascii_graph import Pyasciigraph
import json
'''
install 2 package ascii_graph and SPARQLWrapper with pip before running
'''
endpoint = "https://query.wikidata.org/sparql"
sparql = SPARQLWrapper(endpoint)
sparql.setQuery("""SELECT ?state_of_Malaysia ?state_of_MalaysiaLabel ?area WHERE {
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
?state_of_Malaysia wdt:P31 wd:Q15063586.
OPTIONAL { ?state_of_Malaysia wdt:P2046 ?area. }
}
ORDER BY(?area)
LIMIT 100""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
data = {}
chart_data = []
for result in results["results"]["bindings"]:
data[result["state_of_MalaysiaLabel"]["value"]] = int(result["area"]["value"])
chart_data.append((result["state_of_MalaysiaLabel"]["value"], int(result["area"]["value"])))
print(data)
json.dump(data, open("malaysia_state_size.json", "wb"))
graph = Pyasciigraph()
for line in graph.graph('Size of Malaysia State', chart_data):
print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment