{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Markov Chains\n", "\n", "Play with this step by step walk through of how it works. Let's make a tiny chain." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from random import choice\n", "\n", "book = \"\"\"Would you could you in a house?\n", "Would you could you with a mouse?\n", "Would you could you in a box?\n", "Would you could you with a fox?\n", "Would you like green eggs and ham?\n", "Would you like them, Sam I am?\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's split the book into a list of words:\n", "words = book.split()\n", "words" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def make_chains(text_string):\n", " chains = {}\n", " words = text_string\n", " \n", " # Loop over the words:\n", " for n in range(len(text_string) - 2):\n", " # Get the first and second words and put them into a tuple. They will act as keys in the chain:\n", " key = (words[n], words[n+1],)\n", " value = words[n+2]\n", "\n", " # See if the key is already there\n", " if key not in chains.keys():\n", " # If it's not, initialize it's value to an empty list so we can insert words into it later\n", " chains[key] = []\n", "\n", " # Finally, add the next word to our keys\n", " chains[key].append(value)\n", "\n", " return chains\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def make_text(chains):\n", " \"\"\"Return text from chains.\"\"\"\n", "\n", " # Choose a random key from the chain to start\n", " key = choice(list(chains.keys()))\n", " \n", " # Create our new text that we can add to and return later\n", " text = [key[0], key[1]]\n", "\n", " # Choose a random value from the key in our chain\n", " word = choice(chains[key])\n", "\n", " # This loop will try to visit every key.\n", " while word is not None:\n", " # Form the next key\n", " key = (key[1], word)\n", " # Add the current word to the list\n", " text.append(word)\n", " # Get a new rand word from the new key\n", " word = choice(chains[key])\n", "\n", " # Finally return the new text!\n", " return \" \".join(text)\n", "\n", "\n", "print(make_text(chains))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "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.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }