{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Assignment 1\n",
    "\n",
    "In this assignment, you'll be working with messy medical data and using regex to extract relevant infromation from the data. \n",
    "\n",
    "Each line of the `dates.txt` file corresponds to a medical note. Each note has a date that needs to be extracted, but each date is encoded in one of many formats.\n",
    "\n",
    "The goal of this assignment is to correctly identify all of the different date variants encoded in this dataset and to properly normalize and sort the dates. \n",
    "\n",
    "Here is a list of some of the variants you might encounter in this dataset:\n",
    "* 04/20/2009; 04/20/09; 4/20/09; 4/3/09\n",
    "* Mar-20-2009; Mar 20, 2009; March 20, 2009;  Mar. 20, 2009; Mar 20 2009;\n",
    "* 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009\n",
    "* Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009\n",
    "* Feb 2009; Sep 2009; Oct 2010\n",
    "* 6/2008; 12/2009\n",
    "* 2009; 2010\n",
    "\n",
    "Once you have extracted these date patterns from the text, the next step is to sort them in ascending chronological order accoring to the following rules:\n",
    "* Assume all dates in xx/xx/xx format are mm/dd/yy\n",
    "* Assume all dates where year is encoded in only two digits are years from the 1900's (e.g. 1/5/89 is January 5th, 1989)\n",
    "* If the day is missing (e.g. 9/2009), assume it is the first day of the month (e.g. September 1, 2009).\n",
    "* If the month is missing (e.g. 2010), assume it is the first of January of that year (e.g. January 1, 2010).\n",
    "* Watch out for potential typos as this is a raw, real-life derived dataset.\n",
    "\n",
    "With these rules in mind, find the correct date in each note and return a pandas Series in chronological order of the original Series' indices.\n",
    "\n",
    "For example if the original series was this:\n",
    "\n",
    "    0    1999\n",
    "    1    2010\n",
    "    2    1978\n",
    "    3    2015\n",
    "    4    1985\n",
    "\n",
    "Your function should return this:\n",
    "\n",
    "    0    2\n",
    "    1    4\n",
    "    2    0\n",
    "    3    1\n",
    "    4    3\n",
    "\n",
    "Your score will be calculated using [Kendall's tau](https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient), a correlation measure for ordinal data.\n",
    "\n",
    "*This function should return a Series of length 500 and dtype int.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0         03/25/93 Total time of visit (in minutes):\\n\n",
       "1                       6/18/85 Primary Care Doctor:\\n\n",
       "2    sshe plans to move as of 7/8/71 In-Home Servic...\n",
       "3                7 on 9/27/75 Audit C Score Current:\\n\n",
       "4    2/6/96 sleep studyPain Treatment Pain Level (N...\n",
       "5                    .Per 7/06/79 Movement D/O note:\\n\n",
       "6    4, 5/18/78 Patient's thoughts about current su...\n",
       "7    10/24/89 CPT Code: 90801 - Psychiatric Diagnos...\n",
       "8                         3/7/86 SOS-10 Total Score:\\n\n",
       "9             (4/10/71)Score-1Audit C Score Current:\\n\n",
       "dtype: object"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "doc = []\n",
    "with open('dates.txt') as file:\n",
    "    for line in file:\n",
    "        doc.append(line)\n",
    "\n",
    "df = pd.Series(doc)\n",
    "df.head(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def date_sorter():\n",
    "    \n",
    "    regex1 = '(\\d{1,2}[/-]\\d{1,2}[/-]\\d{2,4})'\n",
    "    regex2 = '((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\\S]*[+\\s]\\d{1,2}[,]{0,1}[+\\s]\\d{4})'\n",
    "    regex3 = '(\\d{1,2}[+\\s](?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\\S]*[+\\s]\\d{4})'\n",
    "    regex4 = '((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[\\S]*[+\\s]\\d{4})'\n",
    "    regex5 = '(\\d{1,2}[/-][1|2]\\d{3})'\n",
    "    regex6 = '([1|2]\\d{3})'\n",
    "    full_regex = '(%s|%s|%s|%s|%s|%s)' %(regex1, regex2, regex3, regex4, regex5, regex6)\n",
    "    parsed_date = df.str.extract(full_regex)\n",
    "    parsed_date = parsed_date.iloc[:,0].str.replace('Janaury', 'January').str.replace('Decemeber', 'December')\n",
    "    parsed_date = pd.Series(pd.to_datetime(parsed_date))\n",
    "    parsed_date = parsed_date.sort_values(ascending=True).index\n",
    "    return pd.Series(parsed_date.values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:10: FutureWarning: currently extract(expand=None) means expand=False (return Index/Series/DataFrame) but in a future version of pandas this will be changed to expand=True (return DataFrame)\n",
      "  # Remove the CWD from sys.path while we load stuff.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0        9\n",
       "1       84\n",
       "2        2\n",
       "3       53\n",
       "4       28\n",
       "5      474\n",
       "6      153\n",
       "7       13\n",
       "8      129\n",
       "9       98\n",
       "10     111\n",
       "11     225\n",
       "12      31\n",
       "13     171\n",
       "14     191\n",
       "15     486\n",
       "16     335\n",
       "17     415\n",
       "18      36\n",
       "19     405\n",
       "20     323\n",
       "21     422\n",
       "22     375\n",
       "23     380\n",
       "24     345\n",
       "25      57\n",
       "26     481\n",
       "27     436\n",
       "28     104\n",
       "29     299\n",
       "      ... \n",
       "470    220\n",
       "471    208\n",
       "472    243\n",
       "473    139\n",
       "474    320\n",
       "475    383\n",
       "476    244\n",
       "477    286\n",
       "478    480\n",
       "479    431\n",
       "480    279\n",
       "481    198\n",
       "482    381\n",
       "483    463\n",
       "484    366\n",
       "485    439\n",
       "486    255\n",
       "487    401\n",
       "488    475\n",
       "489    257\n",
       "490    152\n",
       "491    235\n",
       "492    464\n",
       "493    253\n",
       "494    427\n",
       "495    231\n",
       "496    141\n",
       "497    186\n",
       "498    161\n",
       "499    413\n",
       "Length: 500, dtype: int64"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "date_sorter()"
   ]
  }
 ],
 "metadata": {
  "coursera": {
   "course_slug": "python-text-mining",
   "graded_item_id": "LvcWI",
   "launcher_item_id": "krne9",
   "part_id": "Mkp1I"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "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.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
