yaml2ttl.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python3
  2. import rdflib
  3. import yaml
  4. from rdflib import BNode, Graph, Literal, Namespace, URIRef
  5. from rdflib.namespace import RDF
  6. yaml_file = 'library.yaml'
  7. turtle = Graph ()
  8. LIBRARY = Namespace ('dokk:library:')
  9. SCHEMA = Namespace ('http://schema.org/')
  10. SPDX = Namespace ('http://spdx.org/rdf/terms#')
  11. turtle.bind ('schema', SCHEMA)
  12. turtle.bind ('spdx', SPDX)
  13. with open (yaml_file, 'r') as stream:
  14. try:
  15. library = yaml.load (stream)
  16. except yaml.YAMLError as exc:
  17. print (exc)
  18. for id in library:
  19. turtle.add ((LIBRARY[id],
  20. RDF.type,
  21. URIRef (SCHEMA.CreativeWork)))
  22. turtle.add ((LIBRARY[id],
  23. SCHEMA.title,
  24. Literal (library[id]['title'])))
  25. turtle.add ((LIBRARY[id],
  26. SCHEMA.identifier,
  27. Literal (id)))
  28. if isinstance (library[id]['copyrightYear'], list):
  29. for year in library[id]['copyrightYear']:
  30. turtle.add ((LIBRARY[id],
  31. SCHEMA.copyrightYear,
  32. Literal (year)))
  33. else:
  34. turtle.add ((LIBRARY[id],
  35. SCHEMA.copyrightYear,
  36. Literal (library[id]['copyrightYear'])))
  37. if isinstance (library[id]['inLanguage'], list):
  38. for language in library[id]['inLanguage']:
  39. turtle.add ((LIBRARY[id],
  40. SCHEMA.inLanguage,
  41. Literal (language)))
  42. else:
  43. turtle.add ((LIBRARY[id],
  44. SCHEMA.inLanguage,
  45. Literal (library[id]['inLanguage'])))
  46. if isinstance (library[id]['keywords'], list):
  47. for keywords in library[id]['keywords']:
  48. turtle.add ((LIBRARY[id],
  49. SCHEMA.keywords,
  50. Literal (keywords)))
  51. else:
  52. turtle.add ((LIBRARY[id],
  53. SCHEMA.keywords,
  54. Literal (library[id]['keywords'])))
  55. if isinstance (library[id]['license'], list):
  56. for license in library[id]['license']:
  57. turtle.add ((LIBRARY[id],
  58. SCHEMA.license,
  59. URIRef (SPDX[license])))
  60. else:
  61. turtle.add ((LIBRARY[id],
  62. SCHEMA.license,
  63. URIRef (SPDX[library[id]['license']])))
  64. turtle.serialize ('library.ttl', 'turtle')