{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Tokenizing" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# define a function to get .txt files in a folder\n", "from os import listdir\n", "def list_textfiles(directory):\n", " \"Return a list of filenames ending in '.txt' in DIRECTORY.\"\n", " textfiles = []\n", " for filename in listdir(directory):\n", " if filename.endswith(\".txt\"):\n", " textfiles.append(directory + \"/\" + filename)\n", " return textfiles \n", " " ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# define a function to read the text in a .txt file\n", "\n", "def read_txt(filename):\n", " try:\n", " f = open(filename,'r')\n", " text = f.read()\n", " finally:\n", " if f:\n", " f.close()\n", " return text" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "448822\n" ] } ], "source": [ "#import harry potter textfiles\n", "filenames = list_textfiles('HP')\n", "corpus = []\n", "for f in filenames:\n", " corpus.append(read_txt(f))\n", "print len(corpus[0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } }, "nbformat": 4, "nbformat_minor": 2 }