Created
February 18, 2022 18:25
-
-
Save nutjob4life/5a8d54b97e332c8101deab43cd6818e4 to your computer and use it in GitHub Desktop.
Show the statements made by some RDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
# | |
# show-statements.py — print some RDF | |
# | |
# To use this: | |
# | |
# python3 -m venv venv | |
# venv/bin/pip install --quiet --upgrade pip setuptools rdflib | |
# venv/bin/python show-statements.py URL | |
import rdflib, argparse | |
def read_rdf(source: str) -> dict: | |
'''Parse the RDF at the given ``source`` and return a dictionary of the statements made. | |
The dictionary is of the form ``{s: {p: [o]}}`` where ``s`` is a subject URI which maps to | |
dictionaries whose keys are ``p`` predicate URIs who map to sequences of ``o`` objects. | |
''' | |
graph = rdflib.Graph() | |
statements = {} | |
graph.parse(source) | |
for subject, predicate, obj in graph: | |
predicates = statements.get(subject, {}) | |
objs = predicates.get(predicate, []) | |
objs.append(obj) | |
predicates[predicate] = objs | |
statements[subject] = predicates | |
return statements | |
def print_statements(statements: dict): | |
'''Print the ``statements`` nicely.''' | |
for subject, predicates in statements.items(): | |
print(f'🆔 SUBJECT f{subject} ' + '⎯' * 20) | |
for predicate, objs in predicates.items(): | |
print(f'\t🏷 Predicate {predicate}') | |
for obj in objs: | |
print(f'\t\t {obj}') | |
print() | |
def main(): | |
'''Parse the RDF on the command line and print it nicely.''' | |
parser = argparse.ArgumentParser(description='Show statements made in an RDF source') | |
parser.add_argument('source', help='URL to an RDF source') | |
args = parser.parse_args() | |
statements = read_rdf(args.source) | |
print_statements(statements) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment