{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Normalization of Nibelungenlied "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import re"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from cltk.tokenize.word import WordTokenizer\n",
    "\n",
    "mhg_tokenizer = WordTokenizer(\"middle_high_german\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['bonjour', 'ok']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mhg_tokenizer.tokenize(\"bonjour ok\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "CONSONANTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x', 'z', 'w']\n",
    "\n",
    "VOWLS = ['a', 'e', 'i', 'o', 'u', 'y', 'æ']\n",
    "abbreviations = {'un–': 'und'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "main_links = [\n",
    "    \"https://www.hs-augsburg.de/~harsch/germanica/Chronologie/12Jh/Nibelungen/nib_c_00.html\",\n",
    "    \"https://www.hs-augsburg.de/~harsch/germanica/Chronologie/12Jh/Nibelungen/nib_b_00.html\",\n",
    "    \"https://www.hs-augsburg.de/~harsch/germanica/Chronologie/12Jh/Nibelungen/nib_a_00.html\",\n",
    "    \"https://www.hs-augsburg.de/~harsch/germanica/Chronologie/12Jh/Nibelungen/nib_n_00.html\"\n",
    "]\n",
    "\n",
    "n_pages = 39"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "retrieved_texts = {}\n",
    "for main_link in main_links:\n",
    "    directory = \"extracted_\"+main_link.split(\"/\")[-1].split(\".\")[0][:-3]\n",
    "    retrieved_texts[main_link] = []\n",
    "    for i in range(1, n_pages+1):\n",
    "        filename = os.path.join(directory, str(i)+\".txt\")\n",
    "        with open(filename, \"r\") as f:\n",
    "            retrieved_texts[main_link].append([[mhg_tokenizer.tokenize(half_line) for half_line in line.split('\\t')] for line in f.read().split('\\n')])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[['UNS', 'IST>', 'In', 'alten'], ['mæren', 'wnders', 'vil', 'geseit']],\n",
       " [['von', 'heleden', 'lobebæren'], ['von', 'grozer', 'arebeit']],\n",
       " [['von', 'frevde', 'vn–', 'hochgeciten'], ['von', 'weinen', 'vn–', 'klagen']],\n",
       " [['von', 'kvner', 'recken', 'striten'],\n",
       "  ['mvget', 'ir', 'nv', 'wnder', 'horen', 'sagen']],\n",
       " [['Ez', 'whs', '<inBvregonden>'], ['ein', 'vil', 'edel', 'magedin']],\n",
       " [['daz', 'in', 'allen', 'landen'], ['niht', 'schoners', 'mohte', 'sin']],\n",
       " [['Chriemhilt', 'geheizen'], ['div', 'wart', 'ein', 'schone', 'wip']],\n",
       " [['dar', 'vmbe', 'mvsin', 'degene'], ['vil', 'verliesen', 'den', 'lip']],\n",
       " [['Ir', 'pflagen', 'dri', 'kunige'], ['edel', 'un–', 'rich']],\n",
       " [['Gunther', 'un–', 'Gernot'], ['die', 'rechen', 'lobelich']]]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retrieved_texts[main_links[0]][0][:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Character-level normalization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def conditional_substitution(before, after, source, target, token):\n",
    "    context = \"\"\n",
    "    transformed_context = \"\"\n",
    "    \n",
    "    if before:\n",
    "        if type(before) == list:\n",
    "            context += '(?<before>['+''.join(before)+'])'\n",
    "        elif type(before) == str:\n",
    "            context += '(?<before>['+before+'])'\n",
    "        transformed_context += '\\g<before>'\n",
    "        \n",
    "    context += source\n",
    "    transformed_context += target\n",
    "    \n",
    "    if after:\n",
    "        if type(after) == list:\n",
    "            context += '(?P<after>['+''.join(after)+'])'\n",
    "        elif type(after) == str:\n",
    "            context += '(?P<after>['+after+'])'\n",
    "        transformed_context += '\\g<after>'\n",
    "        \n",
    "    return re.sub(context, transformed_context, token)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'under'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conditional_substitution(None, CONSONANTS, \"w\", \"u\", \"wnder\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'under'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "re.sub(' w(?P<CONSONANTS>['+''.join(CONSONANTS)+'])', 'u\\g<CONSONANTS>', ' wnder')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def normalize_word(word):\n",
    "    res = []\n",
    "    n = len(word)\n",
    "#     for i, j in zip(range(n-1), range(1, n)):\n",
    "    for i in range(n):\n",
    "        c = word[i]        \n",
    "        if i == 0:\n",
    "            before = None\n",
    "            after = word[0]\n",
    "        elif i == n-1:\n",
    "            before = word[n-1]\n",
    "            after = None\n",
    "            \n",
    "        else:\n",
    "            pass\n",
    "        target = \"\"\n",
    "#         res.append(conditional_substitution(before, after, c, target, word))\n",
    "            \n",
    "#         print(i, j)\n",
    "        \n",
    "    return res\n",
    "        \n",
    "#         conditional_substitution()\n",
    "normalize_word(\"bonjour\")\n",
    "    \n",
    "def normalize_book(book):\n",
    "    res = []\n",
    "    for i, chapter in enumerate(book):\n",
    "        res.append([])\n",
    "        for j, stanza in enumerate(chapter):\n",
    "            res[i].append([])\n",
    "            for k, line in enumerate(stanza):\n",
    "                res[i][j].append([])\n",
    "                for l, half_line in enumerate(line):\n",
    "                    res.append[i][j][k].append([])\n",
    "                    for m, word in enumerate(half_line):\n",
    "                        res[i][j][k][l].append()\n",
    "                \n",
    "    l = []\n",
    "    for part in line:\n",
    "        re.sub(' w(?<CONSONANTS>['+''.join(CONSONANTS)+'])', 'u\\g<CONSONANTS>', line)\n",
    "        part.lower()\n",
    "        l.append()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Environment (old_norse_notebook)",
   "language": "",
   "name": "old_norse_notebook"
  },
  "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.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
