Skip to content

Instantly share code, notes, and snippets.

@brianspiering
Created June 17, 2022 15:45
Show Gist options
  • Save brianspiering/bb3af797890ca03d2c8c6942cd3fe5b3 to your computer and use it in GitHub Desktop.
Save brianspiering/bb3af797890ca03d2c8c6942cd3fe5b3 to your computer and use it in GitHub Desktop.
Convert data into ontology
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "25ade2ba",
"metadata": {},
"source": [
"Convert data from web scraping into a ontology\n",
"-----"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "397c5a5a",
"metadata": {},
"outputs": [],
"source": [
"relationships = [[\"Ulta\", \"hasCategory\", \"Men\"],\n",
" [\"Ulta\", \"hasCategory\", \"Skin Care\"],\n",
" [\"Ulta\", \"hasCategory\", \"Gifts\"],\n",
" [\"Ulta\", \"hasCategory\", \"Tools & Brushes\"],\n",
" [\"Men\", \"hasCategory\", \"Shaving\"],\n",
" [\"Men\", \"hasCategory\", \"Cologne\"],\n",
" [\"Shaving\", \"hasCategory\", \"Aftershave\"],\n",
" [\"Shaving\", \"hasCategory\", \"Beard Care\"],\n",
" [\"Shaving\", \"hasCategory\", \"Shaving Cream & Razors\"],\n",
" [\"Gifts\", \"hasCategory\", \"Nail Gifts\"],\n",
" [\"Gifts\", \"hasCategory\", \"Skin Gifts\"],\n",
" [\"Gifts\", \"hasCategory\", \"ULTA Gifts\"],\n",
" [\"Gifts\", \"hasCategory\", \"Makeup Gifts\"],\n",
" ]\n",
"\n",
"ontology = {'Ulta': {'Gifts', 'Men', 'Skin Care', 'Tools & Brushes'},\n",
" 'Men': {'Cologne', 'Shaving'},\n",
" 'Shaving': {'Aftershave', 'Beard Care', 'Shaving Cream & Razors'},\n",
" 'Gifts': {'Makeup Gifts', 'Nail Gifts', 'Skin Gifts', 'ULTA Gifts'}}"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "69cc4f16",
"metadata": {},
"outputs": [],
"source": [
"from collections import defaultdict\n",
"from typing import List\n",
"\n",
"def make_ontology(relationships: List[List[str]]) -> dict:\n",
" \"Given a rdf triple convert to parent(key) and child (value) relationships\"\n",
" \n",
" ontology = defaultdict(set)\n",
"\n",
" for row in relationships:\n",
" parent, _, child = row\n",
" ontology[parent].add(child)\n",
"\n",
" return ontology\n",
"\n",
"assert make_ontology(relationships) == ontology"
]
},
{
"cell_type": "markdown",
"id": "ac911b31",
"metadata": {},
"source": [
"<br>\n",
"<br> \n",
"<br>\n",
"\n",
"----"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.13"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment