Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# coding: utf-8
from SPARQLWrapper import SPARQLWrapper, JSON
import pygraphviz as pgv
# sparql endpointの設定
sparql = SPARQLWrapper("http://ja.dbpedia.org/sparql")
sparql.setQuery("""
SELECT DISTINCT ?label ?iblabel
WHERE {
?s rdf:type dbpedia-owl:ProgrammingLanguage;
rdfs:label ?label.
OPTIONAL {
?s dbpedia-owl:influencedBy ?influencedBy.
?influencedBy rdfs:label ?iblabel.
}.
}
ORDER BY ?label
""")
# JSON形式に変換
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
iDict = {}
ibDict = {}
keys = []
for result in results["results"]["bindings"]:
keys.append(result["label"]["value"])
if result.get("iblabel"):
ibDict.setdefault(result["label"]["value"], []).append(result["iblabel"]["value"])
keys = list(set(keys))
keys.sort()
for key in keys:
print key.encode("utf-8") , ":",
if ibDict.get(key):
for value in ibDict.get(key):
print value.encode("utf-8") , ",",
print ""
# graphvizを使ってグラフを作成する
G = pgv.AGraph(resolution="100", directed=True)
G.add_nodes_from(keys, fontname='Monospace')
for key in keys:
if ibDict.get(key):
for value in ibDict.get(key):
G.add_edge(key, value)
G.layout(prog="dot")
G.draw('./sample.pdf')
print 'Successfully generate the graph.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.