Created
July 23, 2021 08:21
-
-
Save sbp/57d4785ed46ea7039a5606fd9752b10f to your computer and use it in GitHub Desktop.
Script to convert IANA link relations CSV to JSON-LD
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
#!/usr/bin/env python3 | |
""" | |
Usage: ./rels.py link-relations-1.csv URL | |
URL should be e.g. 'http://www.example.org/assignments/relation/#' | |
""" | |
from typing import Any, Dict, Iterator, List | |
def stream(f: Iterator[str], base: str) -> Iterator[Dict[str, str]]: | |
from csv import reader | |
i: int | |
for (i, row) in enumerate(reader(f)): | |
if (not i) or (len(row) != 4): | |
continue | |
datum: Dict[str, str] = { | |
"@id": base + row[0], | |
"label": row[0], | |
} | |
if row[1]: | |
datum["description"] = row[1] | |
if row[2]: | |
datum["citation"] = row[2] | |
if row[3]: | |
datum["note"] = row[3] | |
yield datum | |
def main() -> None: | |
from json import dumps | |
from sys import argv | |
filename: str = argv[1] | |
data: Dict[str, List[Any]] = { | |
"@context": [ | |
{"citation": "http://purl.org/dc/terms/bibliographicCitation"}, | |
{"description": "http://purl.org/dc/terms/description"}, | |
{"label": "http://www.w3.org/2000/01/rdf-schema#label"}, | |
{"note": "http://www.w3.org/2004/02/skos/core#note"}, | |
], | |
"@graph": [], | |
} | |
with open(filename, newline="", encoding="utf-8", errors="replace") as f: | |
for datum in stream(f, argv[2]): | |
data["@graph"].append(datum) | |
print(dumps(data, indent=" ")) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment