{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chapitre 7 : \"Accès aux données\" - solutions\n",
    "\n",
    "---\n",
    "\n",
    "<table class=\"appbclp1\">\n",
    "<tr> <td style=\"font-weight: bold!;\">auteurs :</td><td style=\"text-align: left!;\">Laurent Pointal &lt;<a href=\"mailtp:laurent.pointal@limsi.fr\">laurent.pointal@limsi.fr</a>&gt; &amp; Bob Cordeau &lt;<a href=\"pycours@kordeo.eu\">pycours@kordeo.eu</a>&gt; </td> </tr>\n",
    "<tr> <td style=\"font-weight: bold!;\">licence :</td><td style=\"text-align: left!;\">Creative Commons Attribution-ShareAlike 4.0 International Public License (CC BY-SA 4.0) </td> </tr>\n",
    "<tr> <td style=\"font-weight: bold!;\">source :</td><td style=\"text-align: left!;\"><a href=\"https://github.com/lpointal/appbclp\">https://github.com/lpointal/appbclp</a></td> </tr>\n",
    "<tr> <td style=\"font-weight: bold!;\">description :</td><td style=\"text-align: left!;\">Les programmes dans ce Notebook Jupyter servent de support au livre <span style=\"font-style: italic!;\">« Python 3 - Apprendre à  programmer dans l'écosystème Python»</span>, édition Dunod, dans lequel les différentes sections sont expliquées </td> </tr>\n",
    "<tr> <td style=\"font-weight: bold!;\">url :</td><td style=\"text-align: left!;\"><a href=\"https://www.dunod.com/sciences-techniques/python-3\">https://www.dunod.com/EAN/9782100809141</a></td> </tr>\n",
    "</table>\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_01"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_01\n",
    "\n",
    "def lecture(nomfic):\n",
    "    f = open(nomfic, 'r', encoding='utf-8')\n",
    "    lst = []\n",
    "    prendre = True\n",
    "    for ligne in f:\n",
    "        if prendre:\n",
    "            lst.append(ligne[:-1])\n",
    "        prendre = not prendre\n",
    "    f.close()\n",
    "    return lst\n",
    "lecture(\"../data/indata_exo07_sandmusset.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_02"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_02\n",
    "\n",
    "def ecriture(nomfic, lstnoms):\n",
    "    f = open(nomfic, \"w\", encoding=\"utf8\")\n",
    "    for i, nom in enumerate(lstnoms):\n",
    "        s = \"{}:{}\\n\".format(i+1, nom)\n",
    "        f.write(s)\n",
    "    f.close()\n",
    "    \n",
    "ecriture(\"../data/out_exo07_02_test.txt\", [\"Yves\", \"Maude\", \"Heinrich\", \"Fiona\", \"Malik\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_03"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_03\n",
    "\n",
    "def combine(nom1, nom2):\n",
    "    f1 = open(nom1, 'r', encoding='utf8')\n",
    "    f2 = open(nom2, 'r', encoding='utf8')\n",
    "    while True:\n",
    "        l1 = f1.readline()\n",
    "        l2 = f2.readline()\n",
    "        if not l1 and not l2: \n",
    "            break\n",
    "        if l1.endswith('\\n'):\n",
    "            l1 = l1[:-1]\n",
    "        if l2.endswith('\\n'):\n",
    "            l2 = l2[:-1]\n",
    "        print(l1, l2)\n",
    "    f2.close()\n",
    "    f1.close()\n",
    "    \n",
    "combine(\"../data/indata_exo07_tablette1.txt\", \"../data/indata_exo07_tablette2.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_04"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_04\n",
    "\n",
    "def stocke_points(nom, lst):\n",
    "    f = open(nom, \"w\", encoding=\"utf8\")\n",
    "    for x, y, z in lst:\n",
    "        s = \"{};{};{}\\n\".format(x, y, z)\n",
    "        f.write(s)\n",
    "    f.close()\n",
    "    \n",
    "stocke_points(\"../data/exo07out__04_test.txt\", \n",
    "              [(0.0, 0.0, 0.0), (-1.5, 1.2, -3.4), \n",
    "              (12.78, -4.25, 11.32), (0.03, -3e-2, 11.4)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_05"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_05\n",
    "\n",
    "def charge_points(nom):\n",
    "    f = open(nom, \"r\", encoding=\"utf8\")\n",
    "    lst = []\n",
    "    for ligne in f:\n",
    "        items = ligne.split(';')\n",
    "        items = [float(item) for item in items]\n",
    "        lst.append(tuple(items))\n",
    "    f.close()\n",
    "    return lst\n",
    "\n",
    "charge_points(\"../data/indata_exo05_points.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_06"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_06\n",
    "\n",
    "def copie_debut(nomsrc, nomdst, n=10):\n",
    "    fsrc = open(nomsrc, \"r\", encoding=\"utf8\")\n",
    "    fdst = open(nomdst, \"w\", encoding=\"utf8\")\n",
    "    for ligne in fsrc:\n",
    "        fdst.write(ligne)\n",
    "        n -= 1\n",
    "        if n == 0 :\n",
    "            break\n",
    "    fdst.close()\n",
    "    fsrc.close()\n",
    "    \n",
    "copie_debut(\"../data/indata_exo05_lievretortue.txt\", \"../data/out_exo05_06_test.txt\", 7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_07       "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_07\n",
    "\n",
    "def copie_fin(nomsrc, nomdst, n=10):\n",
    "    # Chargement des n dernières lignes.\n",
    "    fsrc = open(nomsrc, \"r\", encoding=\"utf8\")\n",
    "    memo = []\n",
    "    for ligne in fsrc:\n",
    "        memo.append(ligne)\n",
    "        if len(memo) > n:\n",
    "            del memo[0]\n",
    "    fsrc.close()\n",
    "    # Écriture de ces lignes.\n",
    "    fdst = open(nomdst, \"w\", encoding=\"utf8\")\n",
    "    for ligne in memo:\n",
    "        fdst.write(ligne)\n",
    "    fdst.close()\n",
    "    \n",
    "copie_fin(\"../data/indata_exo05_bateauivre.txt\", \"../data/out_exo05_07_test.txt\", 9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_08"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_08\n",
    "\n",
    "def charge_dico(nom):\n",
    "    d = {}\n",
    "    f = open(nom, encoding=\"utf8\")\n",
    "    for ligne in f:\n",
    "        if not ligne:\n",
    "            continue\n",
    "        cle, val = ligne.split('=', 1)\n",
    "        if val.endswith('\\n'):\n",
    "            val = val[:-1]\n",
    "        d[cle.strip()] = val.strip()\n",
    "    f.close()\n",
    "    return d\n",
    "\n",
    "charge_dico(\"../data/indata_exo05_depts.txt\")\n",
    "charge_dico(\"../data/indata_exo05_equa.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_09"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_09\n",
    "\n",
    "def sauve_dico(nom, dico):\n",
    "    f = open(nom, \"w\", encoding=\"utf8\")\n",
    "    for cle in sorted(dico.keys()):\n",
    "        valeur = dico[cle]\n",
    "        f.write(\"{}={}\\n\".format(cle, valeur))\n",
    "    f.close()\n",
    "    \n",
    "sauve_dico(\"../data/out_exo05_09_test.txt\", dict(un=\"one\", deux=\"two\", onze=\"eleven\", calculquatre=\"4 = 2 + 2\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_10\n",
    "\n",
    "def compte_lignes(nom):\n",
    "    f = open(nom, encoding=\"utf8\")\n",
    "    n = 0\n",
    "    for ligne in f:\n",
    "        n += 1\n",
    "    f.close()\n",
    "    return n\n",
    "\n",
    "compte_lignes(\"../data/indata_exo05_blablator.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_11"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_11\n",
    "\n",
    "def trouve_index(nom, cible):\n",
    "    lst = []\n",
    "    f = open(nom, encoding=\"utf8\")\n",
    "    for n, ligne in enumerate(f):\n",
    "        if cible in ligne:\n",
    "            lst.append(n + 1)\n",
    "    f.close()\n",
    "    return lst\n",
    "\n",
    "trouve_index(\"../data/indata_exo05_blablator.txt\", \"Tout le monde sait\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_12"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_12\n",
    "\n",
    "def stocke_index(nomsrc, nomdst, cible):\n",
    "    fsrc = open(nomsrc, encoding=\"utf8\")\n",
    "    fdst = open(nomdst, \"w\", encoding=\"utf8\")\n",
    "    for n, ligne in enumerate(fsrc):\n",
    "        if cible in ligne:\n",
    "            fdst.write(str(n + 1) + '\\n')\n",
    "    fdst.close()\n",
    "    fsrc.close()\n",
    "    \n",
    "stocke_index(\"../data/indata_exo05_blablator.txt\", \"../data/out_exo05_12_test.txt\", \"Tout le monde sait\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_13"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_13\n",
    "\n",
    "def somcol(nom):\n",
    "    lstsom = None\n",
    "    f = open(nom, encoding=\"utf8\")\n",
    "    for ligne in f:\n",
    "        valstr = ligne.split()  # découpe sur… les suites de blancs\n",
    "        valnum = [float(x) for x in valstr]\n",
    "        if lstsom is None:\n",
    "            lstsom = valnum\n",
    "        else:\n",
    "            for i in range(len(lstsom)):\n",
    "                lstsom[i] += valnum[i]\n",
    "    f.close()\n",
    "    return lstsom\n",
    "\n",
    "somcol(\"../data/indata_exo05_popsurf.txt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_14"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_14\n",
    "\n",
    "# Fonction\n",
    "def filtre(nom_fic_lire, nom_fic_ecrire, seuil_bas, seuil_haut):\n",
    "    f_in = open(nom_fic_lire, encoding=\"utf8\")\n",
    "    f_out = open(nom_fic_ecrire, 'w', encoding=\"utf8\")\n",
    "    for x in f_in:\n",
    "        f_x = float(x)\n",
    "        if (f_x < seuil_bas) or (f_x > seuil_haut):\n",
    "            f_out.write('{}\\n'.format(str(f_x)))\n",
    "    f_out.close()\n",
    "    f_in.close()\n",
    "\n",
    "# Auto-test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n",
    "if __name__ == '__main__' :\n",
    "    from random import random\n",
    "    \n",
    "    INTERVALLE = 100.0\n",
    "    f_data_in = '../data/indata_exo05_hors_bande.txt'\n",
    "    f_data_out = '../data/out_exo05_15_res.txt'\n",
    "    \n",
    "    # filtrage\n",
    "    filtre(f_data_in, f_data_out, INTERVALLE*0.3, INTERVALLE*0.7)\n",
    "\n",
    "    print(\"Filtrage terminé.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### exo7_15"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# exo7_15\n",
    "\n",
    "def indexation(nomdata, nomindex):\n",
    "    fdata = open(nomdata, 'r', encoding=\"utf8\")\n",
    "    findex = open(nomindex, 'w', encoding=\"utf8\")\n",
    "    numligne = 1\n",
    "    position = fdata.tell()\n",
    "    ligne = fdata.readline()\n",
    "    while ligne != \"\":\n",
    "        if ligne.startswith(\"%%EXPERIMENT\"):\n",
    "            s = \"{} {}\\n\".format(numligne, position)\n",
    "            findex.write(s)\n",
    "        # On prépare le passage à la ligne suivante.    \n",
    "        numligne += 1       \n",
    "        position = fdata.tell()\n",
    "        ligne = fdata.readline()    \n",
    "    findex.close()\n",
    "    fdata.close()\n",
    "    \n",
    "indexation(\"../data/indata_exo05_expe.txt\", \"../data/out_exo05_15_res.txt\")"
   ]
  }
 ],
 "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.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
