Tokenizing on Whitespace & Punctuation


In [2]:
import nltk
some_text = "This is some #@*!$ text! This can't be right!"
print nltk.word_tokenize(some_text)
print nltk.wordpunct_tokenize(some_text)


['This', 'is', 'some', '#', '@', '*', '!', '$', 'text', '!', 'This', 'ca', "n't", 'be', 'right', '!']
['This', 'is', 'some', '#@*!$', 'text', '!', 'This', 'can', "'", 't', 'be', 'right', '!']

In [3]:
import unicodecsv
from langdetect import detect
with open('7languages.txt', 'rb') as input_file:
    row_reader = unicodecsv.reader(input_file)
    for row in row_reader:
        tokens = nltk.word_tokenize(row[0])
        for t in tokens:
            print t, "|||",
        print


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-3-1226560a2000> in <module>()
      1 import unicodecsv
      2 from langdetect import detect
----> 3 with open('7languages.txt', 'rb') as input_file:
      4     row_reader = unicodecsv.reader(input_file)
      5     for row in row_reader:

IOError: [Errno 2] No such file or directory: '7languages.txt'

Using RosetteAPI to Tokenize


In [ ]:
from rosette.api import API, RosetteParameters
api = API(service_url="https://api.rosette.com/rest/v1", user_key="40fe14de7872ebf3b8c5e11c17fb7a5f")
params = RosetteParameters()
op = api.morphology()
        
with open('7languages.txt', 'rb') as input_file:
    row_reader = unicodecsv.reader(input_file)
    for row in row_reader:
        params["content"] = row[0]
        result = op.operate(params)
        tokens = result['lemmas']
        for t in tokens:
            print t['text'], "|||",
        print

In [ ]:
params["content"] = some_text
result = op.operate(params)
tokens = result['lemmas']
for t in tokens:
    print t['text'], "|||",
print
for t in tokens:
    print t['lemma'], "|||",
print

Exploring Tokens from a NLTK Corpus

Returning the the Gutenberg, get Alice in Wonderland as text and as tokens


In [4]:
from nltk.corpus import gutenberg
alice_raw = gutenberg.raw(fileids=['carroll-alice.txt']).lower()
alice_words = nltk.wordpunct_tokenize(alice_raw) 
alice_vocab = set(alice_words)

Inspect the text


In [5]:
#Looking at the first 100 words
print alice_words[:100]


[u'[', u'alice', u"'", u's', u'adventures', u'in', u'wonderland', u'by', u'lewis', u'carroll', u'1865', u']', u'chapter', u'i', u'.', u'down', u'the', u'rabbit', u'-', u'hole', u'alice', u'was', u'beginning', u'to', u'get', u'very', u'tired', u'of', u'sitting', u'by', u'her', u'sister', u'on', u'the', u'bank', u',', u'and', u'of', u'having', u'nothing', u'to', u'do', u':', u'once', u'or', u'twice', u'she', u'had', u'peeped', u'into', u'the', u'book', u'her', u'sister', u'was', u'reading', u',', u'but', u'it', u'had', u'no', u'pictures', u'or', u'conversations', u'in', u'it', u',', u"'", u'and', u'what', u'is', u'the', u'use', u'of', u'a', u'book', u",'", u'thought', u'alice', u"'", u'without', u'pictures', u'or', u'conversation', u"?'", u'so', u'she', u'was', u'considering', u'in', u'her', u'own', u'mind', u'(', u'as', u'well', u'as', u'she', u'could', u',']

In [6]:
#How many words are in this book? 
print "Raw: ", len(alice_raw)
print "Words: ", len(alice_words)
print "Vacabulary: ", len(alice_vocab)


Raw:  144395
Words:  34110
Vacabulary:  2636

In [7]:
print alice_vocab


set([u'secondly', u'pardon', u'saves', u'knelt', u'four', u'sleep', u'hanging', u'ringlets', u'oldest', u'hate', u'assembled', u'forget', u'whose', u'lory', u'paris', u'blacking', u'presents', u'under', u'inwards', u'sorry', u'worth', u'music', u'rise', u'every', u'jack', u'seals', u'fireplace', u'school', u'prize', u'wooden', u'pinch', u'persisted', u'favoured', u'leaders', u'tired', u'feathers', u'elegant', u'likely', u'louder', u'machines', u'shining', u'even', u'meekly', u'hide', u'pace', u'solemn', u'thunder', u'lizard', u'poison', u'above', u'conduct', u'new', u'ever', u'told', u'join', u'never', u'wrapping', u'here', u'met', u'protection', u'hers', u'cardboard', u'shriek', u'dry', u'daughter', u'leaves', u'changed', u'swam', u'barrowful', u'smoke', u'changes', u'ventured', u'golden', u'ground', u'explained', u'angrily', u'feelings', u'brought', u'patience', u'moral', u'guests', u'drowned', u'punching', u'spoke', u'would', u'arms', u'insult', u'overhead', u'therefore', u'leant', u'fainting', u'tell', u'breathe', u'peeping', u'evening', u'hurt', u'grief', u'glass', u'excellent', u'adjourn', u'hole', u'hold', u'must', u'me', u'word', u'room', u'work', u'dodo', u'worm', u'roof', u'obstacle', u'elbow', u'my', u'shook', u'rosetree', u'quiver', u'serpent', u'give', u'unjust', u'flung', u'frighten', u'want', u'extraordinary', u'keep', u'returned', u'end', u'turn', u'complaining', u'agony', u'returning', u'how', u'hot', u'answer', u'truthful', u'poker', u'flustered', u'mouths', u'lad', u'ladder', u'after', u'wrong', u'jumping', u'lay', u'curiosity', u'law', u'lap', u'attempt', u'childhood', u'wink', u'wriggling', u'green', u'aloud', u'order', u'wind', u'wine', u'executed', u'dreamed', u'over', u'london', u'mabel', u'before', u'chatte', u'fit', u'somewhere', u'lefthand', u'fix', u',', u'writing', u'better', u'fig', u'glanced', u'croquet', u'weeks', u'overcome', u'then', u'them', u'slate', u'safe', u'break', u'caterpillar', u'they', u'interrupt', u'one', u'bank', u'pegs', u'grammar', u'meat', u'alternately', u'leading', u'herald', u'eleventh', u'roast', u'each', u'went', u'side', u'bone', u'mean', u'calmly', u'telescope', u'series', u'dodged', u'vote', u'taught', u'forgot', u'flock', u'sounds', u'reminding', u'velvet', u'tales', u'sighing', u'forty', u'fellows', u'content', u're', u'laid', u'got', u'size', u'splashed', u'stamping', u'turning', u'given', u'free', u'uglification', u'whereupon', u'mallets', u'wanted', u'telescopes', u'enormous', u'ate', u'shelves', u'writhing', u'cackled', u'messages', u'days', u'pence', u'hopeless', u'moving', u'footsteps', u'bite', u'enjoy', u'already', u'dunce', u'curiouser', u'encouraging', u'hearing', u'wash', u'another', u'wasn', u'thoughtfully', u'thick', u'awfully', u'xii', u'top', u'girls', u'airs', u'master', u'too', u'wildly', u'legs', u'bitter', u'dogs', u'listen', u'consented', u'ceiling', u'solemnly', u'took', u'positively', u'character', u'begins', u'distance', u'coward', u'tree', u'second', u'seated', u'shower', u'matter', u'splendidly', u'exclaimed', u'flame', u'friend', u'askance', u'feeling', u'chrysalis', u'ran', u'shyly', u'modern', u'mind', u'mine', u'sorrow', u'talking', u'rat', u'manner', u'seen', u'seem', u'tells', u'eels', u'strength', u'thoroughly', u'-', u'eagerly', u'subjects', u'doors', u'laughed', u'gravy', u'nobody', u'though', u'regular', u'mouth', u'plenty', u'grave', u'zealand', u'don', u'alarm', u'm', u'dog', u'ridiculous', u'sun', u'notion', u'came', u'decidedly', u'saying', u'currants', u'pardoned', u'pope', u'lewis', u'queen', u'sage', u'ending', u'attempts', u'queer', u'earth', u'toast', u'busy', u'spite', u'explain', u'folded', u'sugar', u'deepest', u'disgust', u'do', u'cartwheels', u'squeaking', u'watch', u'coast', u'frowning', u'shutting', u'cushion', u'altogether', u'frying', u'nasty', u'learned', u'bat', u'nicely', u'anxiously', u'shape', u'licking', u'twice', u'bad', u'softly', u'explanations', u'steam', u'ears', u'blew', u'fair', u'doze', u'depends', u'decided', u'flashed', u'cattle', u'miserable', u'mournfully', u'best', u'subject', u'pebbles', u'said', u'away', u'unable', u'finger', u'sorts', u'claws', u'crossly', u'interrupting', u'terms', u'confusion', u'weak', u'however', u'camomile', u'twinkling', u'drew', u'picking', u'improve', u'pity', u'received', u'accident', u'country', u'ill', u'cup', u'adventures', u'edgar', u'players', u'games', u'treacle', u'argue', u'asked', u'tone', u'appeared', u'royal', u'lullaby', u'height', u'wider', u'beheaded', u'speak', u'shouting', u'tarts', u'three', u'been', u'.', u'chimneys', u'much', u'axis', u'interest', u'schoolroom', u'expected', u'?"', u'lovely', u'threw', u'natured', u'life', u'wags', u'mushroom', u'twinkled', u'grunt', u'uncommon', u'child', u'catch', u'doth', u'teapot', u'has', u'lessen', u'tastes', u'air', u'ugly', u'near', u'neat', u'viii', u'stopping', u'voice', u'mistake', u'remembering', u'ix', u'seven', u'fourteenth', u'played', u'is', u'it', u'iv', u'ii', u'gloomily', u'clinging', u'in', u'mouse', u'if', u'grown', u'growl', u'severity', u'things', u'make', u'linked', u'forehead', u'unfortunate', u'vegetable', u'plates', u'several', u'couple', u'bells', u'fairly', u'"\'', u'tops', u'hand', u'delight', u'marched', u'dozing', u'opportunity', u'thoughts', u'kid', u'butter', u'hearth', u'kept', u'matters', u'settled', u'humble', u'rome', u'humbly', u'impertinent', u'hearts', u'the', u'yours', u'left', u'just', u'sentence', u'sleepy', u'atheling', u'verses', u'farther', u'yes', u'yer', u'yet', u'adding', u'spectacles', u"!')", u'hjckrrh', u'cherry', u'had', u'grumbled', u'belongs', u'easy', u'prison', u'save', u'hat', u'gave', u'boxed', u'mayn', u'possible', u'possibly', u'dreamy', u'flamingoes', u'afore', u'judge', u'burnt', u'shoulder', u'sorrows', u'appearing', u'uncivil', u'seaside', u'alice', u'quadrille', u'officer', u'night', u'hung', u'towards', u'right', u'old', u'deal', u'people', u'sends', u'crown', u'somehow', u'dead', u'clubs', u'escape', u'dear', u'straightening', u'bore', u'goldfish', u'creep', u'confusing', u'denies', u'for', u'bottom', u'purple', u'ear', u'everything', u'asking', u'shakespeare', u'denied', u'serpents', u'beating', u'christmas', u'pinched', u'knew', u'burn', u'disappeared', u'lamps', u'losing', u'bowing', u'permitted', u'takes', u'wept', u'theirs', u'newspapers', u'choke', u'o', u'dinner', u'despair', u'sluggard', u'raised', u'sob', u'wasting', u'puzzle', u'delighted', u'cauldron', u'son', u'stop', u'respectable', u'bats', u'balanced', u'frightened', u'cleared', u'crowd', u'wag', u'sneezing', u'fight', u'derision', u'morcar', u'call', u'was', u'happy', u'fork', u'head', u'waistcoat', u'form', u'offer', u'attempted', u'becoming', u'back', u'failure', u'hear', u'heap', u'boon', u'removed', u'true', u'flavour', u'rippling', u'inside', u'until', u'note', u'scream', u'unusually', u'temper', u'proud', u'proved', u'sticks', u'screaming', u'fury', u'toss', u"';", u'muscular', u'drive', u"''", u'howling', u'guessed', u'\'"', u'curious', u'accounting', u"',", u"')", u'floor', u'generally', u'handed', u'tis', u'beheading', u'setting', u'holding', u'tie', u'vanished', u'shrink', u'saucepans', u'picture', u'ferrets', u'pronounced', u'surprise', u'ointment', u'welcome', u'skirt', u'fell', u'ridges', u'inkstand', u'unlocking', u'died', u'puss', u'spades', u'longer', u'together', u'beds', u'longed', u'contemptuous', u'time', u'push', u'treading', u'managed', u'chain', u'whoever', u'dance', u'untwist', u'rudeness', u'invent', u'crocodile', u'mile', u'chair', u'milk', u'row', u"?',", u'certainly', u'father', u'passage', u'answered', u'unpleasant', u'glad', u'terror', u'circumstances', u'jogged', u'fancied', u'brown', u'made', u'keeping', u'hatter', u'choice', u'stays', u'cook', u'ma', u'trouble', u'exact', u'feeble', u'minute', u'cool', u'sighed', u'presented', u'did', u'turns', u'dig', u'brother', u'leave', u'settle', u'quick', u'teaching', u'scaly', u'round', u'prevent', u'brave', u'says', u'tougher', u'sigh', u'sign', u'cost', u'dried', u'eating', u'helpless', u'irritated', u'appear', u'axes', u'lazily', u'goes', u'reply', u'falling', u'geography', u'filled', u'growls', u'jury', u'partners', u'honour', u'v', u'french', u'water', u'twentieth', u'yards', u'hoarse', u'[', u'change', u'wait', u'box', u'sending', u'impatiently', u'lazy', u'wherever', u'gryphon', u'trial', u'jaw', u'usually', u'shifting', u'quarrel', u'useful', u'morals', u'extra', u'hopeful', u'merely', u'marked', u'inquisitively', u'puffed', u'swallowed', u'stingy', u'everybody', u'driest', u'angry', u'visit', u'only', u'france', u'live', u'wood', u'somersault', u'wondering', u'teeth', u'today', u'loving', u'chapter', u'entrance', u'sharing', u'afford', u'flying', u'teases', u'ignorant', u'oop', u'fly', u'deserved', u'pretend', u'longitude', u'cat', u'soup', u'sour', u'can', u'growing', u'making', u'dispute', u'laughter', u'slightest', u'heart', u'crazy', u'frontispiece', u'nursing', u'figure', u'carroll', u'confused', u'paused', u'heard', u'chin', u'dropped', u'counting', u'stole', u'evidently', u'pink', u",'", u',"', u'winter', u'fortunately', u'buttered', u'watching', u'pine', u',)', u'write', u'till', u'fourth', u'stigand', u'condemn', u'may', u'dive', u'spot', u'crashed', u'birthday', u'tipped', u'mad', u'?)', u"?'", u'such', u'grow', u'man', u'scrambling', u'classics', u'natural', u'remember', u'succeeded', u'whenever', u'maybe', u'daisies', u'tale', u'suet', u'so', u'crept', u'offend', u'arrived', u".--'", u'pulled', u'talk', u'recognised', u'shoes', u'seeing', u'indeed', u'pointed', u'canary', u'years', u'course', u'quarrelled', u'shake', u'argued', u'cold', u'still', u'owl', u'birds', u'limbs', u'yawning', u'thank', u'curly', u'interesting', u'curls', u'civil', u'window', u'dreadfully', u'thump', u'ours', u'into', u'happened', u'roses', u'lonely', u'tucked', u'conversations', u'sooner', u'bound', u'underneath', u'tails', u'soo', u'half', u'not', u'now', u'hall', u'nor', u'down', u'execute', u'shouted', u'name', u'chuckled', u'corners', u'drop', u'rock', u'scolded', u'entirely', u'creature', u'em', u'eh', u'bursting', u'beloved', u'hurried', u'goose', u'catching', u'begun', u'year', u'girl', u'worried', u'irons', u'living', u'canvas', u'opened', u'concert', u'abide', u'hastily', u'looking', u'seriously', u'stupid', u'housemaid', u'juror', u'attended', u'state', u'cart', u'quite', u'bringing', u'besides', u'care', u'advance', u'couldn', u".')", u'honest', u'thing', u'place', u'invitation', u'think', u'waited', u'first', u'sprawling', u'arithmetic', u'xi', u'beauti', u'spoken', u'yourself', u'merrily', u'fast', u'directly', u'carry', u'impossible', u'ring', u'open', u'tomorrow', u'cheerfully', u'sheep', u'little', u'checked', u'silent', u'arch', u'caught', u'waist', u'trampled', u'shiver', u'white', u'speaking', u'eyes', u'way', u'mostly', u'that', u'snatch', u'alas', u'eyed', u'editions', u'flowers', u'than', u'wide', u'apples', u'venture', u'were', u'cards', u'wandering', u'and', u'addressing', u'tasted', u'remained', u'ann', u'turned', u'argument', u'voices', u'say', u'anger', u'themselves', u'saw', u'any', u'sat', u'snorting', u'tulip', u'reasonable', u'downwards', u'wandered', u'emphasis', u'hookah', u'take', u'haste', u'encouraged', u'butterfly', u'begin', u'sure', u'altered', u'opposite', u'neatly', u'clearer', u'zigzag', u'printed', u'pair', u'knee', u'educations', u']', u'queens', u'pencils', u'fills', u'considered', u'egg', u'later', u'steady', u'hungry', u'playing', u'managing', u'joys', u'stockings', u'hedgehog', u'salt', u'trembled', u'.]', u'walking', u'show', u'cheap', u'bright', u'corner', u'fifth', u'curled', u'busily', u'nice', u'nodded', u'histories', u'coaxing', u'tears', u'going', u'shrill', u'toffee', u'get', u'between', u'whiles', u'unimportant', u'cannot', u'nearly', u'hedge', u'resource', u'seldom', u'morning', u'miles', u'executes', u'finishing', u'where', u'declared', u'crumbs', u'burst', u'pennyworth', u'fanned', u'asleep', u'wonder', u'ways', u'jumped', u'pencil', u")--'", u'label', u'teacup', u'behind', u'hiss', u'cautiously', u'reading', u'across', u'caucus', u'whispered', u'notice', u'tut', u'queerest', u'killing', u'blame', u'singers', u'come', u'croqueted', u'dates', u'repeating', u"'--", u'cakes', u'many', u'stupidest', u'quiet', u'nile', u'blasts', u'personal', u's', u'loudly', u'disappointment', u'railway', u'expression', u'comes', u'riddle', u'among', u'loveliest', u'afterwards', u'lacie', u'pot', u'pop', u'accusation', u'stretched', u'learning', u'constant', u'precious', u'custody', u'turkey', u'uglify', u'cares', u'suppressed', u'mark', u'breath', u'punished', u'judging', u'hardly', u'mary', u'engine', u'direction', u'thousand', u'flurry', u'wake', u'evidence', u'those', u'case', u'myself', u'folding', u'turtles', u'these', u'sobbed', u'warning', u'slippery', u'antipathies', u'promising', u'squeezed', u'shrieks', u'invited', u'promised', u'rubbing', u'engaged', u'couples', u'middle', u'sudden', u'heels', u'worry', u'different', u'pat', u'paw', u'edwin', u'same', u'speech', u'triumphantly', u'pan', u'week', u'finish', u'nest', u'persons', u'running', u'changing', u'passing', u'complained', u'traps', u'charges', u'no', u'roughly', u'without', u'grinned', u'bottle', u'fidgeted', u'summer', u'being', u'when', u'rest', u'violent', u'growled', u'kill', u'touch', u'exclamation', u'speed', u'sulky', u'blow', u'death', u'dipped', u'hint', u'thinking', u'rose', u'seems', u'except', u'thimble', u'struck', u'bread', u'real', u'around', u'kills', u'desperately', u'read', u'lowing', u'dark', u'politely', u'world', u'earls', u'execution', u'lady', u"('", u'dare', u'tremulous', u'pounds', u'draggled', u'sternly', u't', u'downward', u'passionate', u'reduced', u'twelve', u'shillings', u'lobster', u'respect', u'mustard', u'moon', u'expressing', u'moderate', u'knife', u'considering', u'felt', u'arrow', u'business', u'broken', u'throw', u'on', u'subdued', u'oh', u'of', u');', u'violence', u'shrimp', u'chop', u'boldly', u'journey', u'stand', u'knave', u'act', u'mixed', u'ou', u'or', u'imitated', u'quietly', u'appealed', u'burning', u'trot', u'spreading', u'lifted', u'legged', u'rising', u'dreaming', u'england', u'happening', u'shrinking', u'your', u'her', u'there', u'cats', u'low', u'jaws', u'attends', u'mercia', u'hare', u'mischief', u'jug', u'enough', u'mice', u'trying', u'with', u'feather', u'cheated', u'rush', u'waste', u'arranged', u'tiptoe', u'tones', u'conqueror', u'grass', u'agree', u'gone', u'fright', u'taste', u'ah', u'moved', u'deep', u'fellow', u'as', u'bawled', u'at', u'watched', u'horse', u'tremble', u'again', u'rubbed', u'idiot', u'field', u'remarks', u'you', u'puppy', u'poor', u'oneself', u'inquired', u'uncorked', u'remarked', u'whiskers', u'whistling', u'waving', u'brandy', u'important', u'brass', u'sneeze', u'pool', u'applause', u'wife', u'sobbing', u'tricks', u'sharks', u'having', u'once', u'strings', u'growling', u'all', u'snout', u'consider', u'pointing', u'caused', u'month', u'dish', u'follow', u'faster', u'children', u'whiting', u'conger', u'dreadful', u'ravens', u'remarkable', u'hunting', u'encourage', u'laughing', u'to', u'tail', u'wants', u'crimson', u'smile', u'sound', u'woman', u'worse', u'sitting', u'very', u'fat', u'fan', u'minded', u'hatching', u'fall', u'soles', u'washing', u'--', u'list', u'joined', u'large', u'sang', u'sand', u'small', u'fashion', u'familiarly', u'quicker', u'rats', u'ten', u'tea', u'past', u'rate', u'pass', u'further', u'creatures', u'grinning', u'what', u'stood', u'darkness', u'clock', u'deeply', u'stool', u'stoop', u'northumbria', u'nurse', u'hasn', u'full', u'loose', u'answers', u'hours', u'shouldn', u'affectionately', u'directions', u'handwriting', u'search', u'tortoise', u'difficulty', u'stretching', u')--', u'memorandum', u'soldier', u'murdering', u'narrow', u'followed', u'family', u'suddenly', u'clapping', u'vii', u'usurpation', u'ask', u'toys', u'thatched', u'readily', u'eye', u'proceed', u'injure', u'faint', u'two', u'"!\'', u'splash', u'taken', u'weren', u'more', u'flat', u'wretched', u'door', u'knows', u'company', u'stick', u'broke', u'particular', u'known', u'hurry', u'producing', u'?--', u'cunning', u'gazing', u'none', u'hour', u'sulkily', u'offended', u'remain', u'pressing', u'nine', u'learn', u'knocked', u'furrows', u'history', u'beautiful', u'shark', u'feebly', u'lives', u'gravely', u'rustled', u'share', u'sense', u'sharp', u'garden', u'!', u'needs', u'court', u'advantage', u'rather', u'comfort', u'magpie', u'maps', u'occasionally', u'footman', u'canterbury', u'skurried', u'tried', u'rude', u'suppose', u'advice', u'purring', u'coming', u'gardeners', u'pleaded', u'hedgehogs', u'a', u'short', u'crowded', u'loud', u'ootiful', u'eats', u'perhaps', u'shore', u'shade', u'banks', u'pleasure', u'dream', u'fender', u'replied', u'help', u'incessantly', u'soon', u'held', u'paper', u'through', u'existence', u'smiling', u'its', u'roots', u'fanning', u'rapidly', u'forwards', u'pray', u'buttercup', u'actually', u'late', u'absence', u'parts', u'speaker', u'might', u'arguments', u'wouldn', u'good', u'somebody', u'unrolled', u'ye', u'noticing', u',"\'', u'foot', u'executions', u'mystery', u'easily', u'always', u'rattle', u'fluttered', u'someone', u'stopped', u'die', u'found', u'fairy', u'pleasanter', u'heavy', u'harm', u'begged', u'upstairs', u'house', u'fish', u'hard', u'idea', u'accidentally', u'duchess', u'scratching', u'really', u'anxious', u'dears', u'flower', u'missed', u'wondered', u'rearing', u'since', u'pigeon', u'trusts', u'snappishly', u'pun', u'crouched', u'upon', u'guess', u'pleasant', u'houses', u'reason', u'imagine', u'put', u'rises', u'beginning', u'thrown', u'pairs', u'curtsey', u'terribly', u'expecting', u'w', u'daisy', u'fallen', u'porpoise', u'slipped', u'feel', u'dinn', u'knocking', u'number', u'fancy', u'feet', u'done', u'shilling', u'miss', u'story', u'"', u'heads', u'twenty', u'least', u'paint', u'station', u'passed', u'hundred', u'recovered', u'bowed', u'relieved', u'uncommonly', u'immediate', u'procession', u'luckily', u'part', u'believe', u'stairs', u'king', u'kind', u'grew', u'kindly', u'bag', u'double', u'grey', u'spirited', u'i', u'stalk', u'?"\'', u'treated', u'declare', u'executioner', u'picked', u'dainties', u'livery', u'murder', u'fading', u'sell', u'lie', u'dancing', u'commotion', u'officers', u'lit', u'swallowing', u'breeze', u'finding', u'relief', u'play', u'added', u'reality', u'eggs', u'english', u'reach', u'most', u'plan', u'eaten', u'nothing', u'extremely', u'oyster', u'mineral', u'clear', u'sometimes', u'clean', u'daresay', u'lying', u'ugh', u'languid', u'fond', u'idiotic', u'carefully', u'croqueting', u'fine', u'find', u'faces', u'rocket', u'grazed', u'justice', u'nervous', u'unwillingly', u'unhappy', u'pretty', u'circle', u'shepherd', u'his', u'hit', u'meanwhile', u'trees', u'whistle', u'courage', u'hid', u'pretending', u'shared', u'him', u'chimney', u'distraction', u'cry', u'doubled', u'gloves', u'common', u'x', u'engraved', u'nibbled', u'wrote', u'set', u'signify', u'throwing', u'see', u'hoarsely', u'are', u'sea', u'close', u'bark', u'arm', u'feared', u'youth', u'learnt', u'lastly', u'pictures', u'wow', u'please', u'won', u'various', u'guilt', u'arrum', u'kneel', u'meal', u'knowing', u'latin', u'timidly', u'vanishing', u'both', u'c', u'last', u'riddles', u'panther', u'dismay', u'became', u'forgotten', u'whole', u'finds', u'tittered', u'sentenced', u'liked', u'):', u'majesty', u'drunk', u'simple', u'sweet', u'manners', u'whatever', u'hollow', u'alone', u'unfolded', u'simply', u'),', u').', u'supple', u'along', u'patiently', u'acceptance', u'verse', u'whom', u'secret', u'dropping', u'collected', u'meeting', u'empty', u'resting', u'lived', u'gay', u'boy', u'fire', u'ada', u'remark', u'else', u'1865', u'!"?\'', u'mournful', u'furrow', u'stolen', u'fur', u'look', u'raw', u'solid', u'straight', u'bill', u'rope', u'forgetting', u'while', u'pressed', u'leaning', u'fun', u'ful', u'pack', u'swim', u'hoping', u'violently', u'itself', u'beautifully', u'ready', u'kings', u'funny', u'righthand', u'choking', u'grant', u'belong', u'shorter', u'rules', u'grand', u'advise', u'shan', u'used', u'snail', u'yesterday', u'desks', u'patriotic', u'moment', u'flown', u'cucumber', u'purpose', u'uneasily', u'timid', u'lower', u'older', u'person', u'edge', u'grins', u'clasped', u'lobsters', u'listening', u'morsel', u'rumbling', u'questions', u'using', u'love', u'cut', u'cur', u'also', u'hated', u'kissed', u'vague', u'eager', u'grin', u'crying', u'remaining', u'surprised', u'tillie', u'australia', u'march', u'showing', u'pattering', u'game', u'entangled', u'bit', u'wings', u'like', u'knock', u'd', u'shaped', u'follows', u'chorus', u'eel', u'provoking', u'foolish', u'walrus', u'often', u'obliged', u'lodging', u'some', u'remarking', u'understood', u'lips', u'marmalade', u'hurriedly', u'sight', u'wonderland', u'candle', u'capering', u'pale', u'ourselves', u'saucer', u'savage', u'scale', u'twinkle', u'pet', u'shall', u'quickly', u'lark', u'either', u'be', u'run', u'remembered', u'salmon', u'refused', u'nowhere', u'ache', u'by', u'comfits', u'bristling', u'anything', u'wore', u'prove', u'straightened', u'needn', u'naturedly', u'shiny', u'bleeds', u'silence', u'undoing', u'letter', u'conquest', u'within', u'nonsense', u'jurymen', u'piteous', u'frames', u'lesson', u'.)', u'signifies', u'sad', u'."', u'question', u'long', u".'", u'consultation', u'prettier', u'suit', u':', u'himself', u'an', u'inches', u'memory', u'hoped', u'alive', u'atom', u'upright', u'line', u'dull', u'raising', u'peeped', u'directed', u'hush', u'up', u'us', u'accustomed', u'proves', u'called', u'yelled', u'ordered', u'roared', u'doesn', u'skimming', u'graceful', u'denying', u'puzzling', u'backs', u'occasional', u'ornamented', u'nay', u'mock', u'tart', u'brushing', u'draw', u'energetic', u'favourite', u'faintly', u'occurred', u'william', u'meaning', u'smiled', u'fishes', u'song', u'sides', u'ago', u'land', u'e', u'age', u'walked', u'annoyed', u'impatient', u'neighbouring', u'fitted', u'far', u'sounded', u'prizes', u'rabbit', u'splashing', u'sixpence', u'go', u'cupboards', u'seemed', u'peering', u'young', u'send', u'nose', u'pleasing', u'sent', u'retire', u'presently', u'flinging', u'outside', u'panting', u'squeaked', u'spoon', u'putting', u'rattling', u'telling', u'drinking', u'continued', u'severely', u'magic', u'respectful', u'stiff', u'shock', u'try', u'tunnel', u'race', u'verdict', u'insolence', u'concluded', u'smaller', u'uncomfortably', u'sensation', u'boots', u'uncomfortable', u'odd', u'diamonds', u'giving', u'squeeze', u'waiting', u'experiment', u'capital', u';', u'bird', u'poky', u'body', u'lessons', u'melancholy', u'led', u'chose', u'upsetting', u'beasts', u'fifteenth', u'believed', u'let', u'sink', u'others', u'slates', u'sing', u'invented', u'fifteen', u'settling', u'vinegar', u'great', u'didn', u'uneasy', u'involved', u'larger', u'leaving', u'simpleton', u'opinion', u'climb', u'behead', u'makes', u'wig', u'examining', u'apple', u'win', u'disobey', u'manage', u'dormouse', u'addressed', u'names', u'duck', u'doubtfully', u'nibbling', u'singing', u'standing', u'use', u'cheered', u'from', u'archbishop', u'processions', u'frog', u'next', u'few', u'doubt', u'crab', u'doubling', u'eaglet', u'cheeks', u'sort', u'throne', u'clever', u'rich', u'started', u'inclined', u'about', u'carrying', u'labelled', u'sharply', u'baby', u'iii', u'annoy', u'account', u'balls', u'animals', u'panted', u'locks', u'this', u':--', u'shrieked', u'pour', u'curtseying', u'arches', u'anywhere', u'crossed', u'thin', u'meet', u'fetch', u'bend', u'bent', u'reeds', u'plate', u'pocket', u'lock', u'dripping', u'pieces', u'high', u'pulling', u'something', u'bones', u'wonderful', u'paws', u'onions', u'contempt', u'sir', u'curving', u'sit', u'trumpet', u'six', u'delay', u'courtiers', u'animal', u'instead', u'furiously', u'pretexts', u'farm', u'locked', u'waters', u'thunderstorm', u'tied', u'\'"--', u'pigs', u'men', u'minding', u'multiplication', u'terrier', u'patted', u'noises', u'lines', u'interrupted', u'trembling', u'chief', u'allow', u'crawling', u'furious', u'flapper', u'bathing', u'closely', u'reeling', u'move', u'"--', u'produced', u'own', u'mentioned', u'll', u'banquet', u'orange', u'bye', u'crash', u'practice', u'muddle', u'flew', u'cutting', u'kiss', u'hands', u'front', u'day', u'toes', u'sneezed', u'delightful', u'tureen', u'truth', u'accounts', u'sneezes', u'shaking', u'normans', u'brush', u'footmen', u'doing', u'globe', u'books', u'sands', u'thirteen', u'measure', u'our', u'wander', u'witness', u'out', u'sobs', u"'", u'uglifying', u'hedges', u'hatters', u'eyelids', u'barley', u'cause', u'red', u'oblong', u'shut', u'undo', u'attending', u'completely', u'jurors', u'yard', u'gallons', u'could', u'rustling', u'times', u'conversation', u'length', u'trickling', u'sorrowful', u'clamour', u'plainly', u'blown', u'pitied', u'soothing', u'fits', u'howled', u'blows', u'undertone', u'ancient', u'sadly', u'ordering', u'vulgar', u'muttered', u'their', u'perfectly', u'sixteenth', u'explanation', u'exactly', u'branches', u'herself', u'haven', u'neck', u'bother', u'yawned', u'beg', u'submitted', u'bee', u'beautify', u'stupidly', u'listeners', u'result', u'thistle', u'tidy', u'gently', u'comfortable', u'tide', u'comfortably', u'have', u'throat', u'"?\'', u'wearily', u'clearly', u'afraid', u'dishes', u'bough', u'wits', u'able', u'instance', u'sh', u'which', u';--', u'blades', u'_i_', u'unless', u'centre', u'who', u'but', u'prisoner', u'alarmed', u'why', u'deny', u'):--', u'flappers', u'gather', u'upset', u'face', u'looked', u'absurd', u'guinea', u'painting', u'fact', u'affair', u'pleases', u'bring', u'planning', u'soldiers', u'fear', u'pleased', u'chanced', u'nearer', u'pause', u'knowledge', u'hadn', u'(', u'jar', u'should', u'buttons', u'smallest', u'fumbled', u'handsome', u'hope', u'indignant', u'meant', u'prosecute', u'listened', u'means', u'beat', u'beau', u'muttering', u'bear', u'ones', u'words', u'beak', u'doubtful', u'brain', u'shy', u'calling', u'stuff', u'she', u'rapped', u'fixed', u'shedding', u'!--', u'tossing', u'frame', u'we', u'indignantly', u'desperate', u'forepaws', u'closer', u'coils', u'pattern', u'drawling', u'written', u'difficulties', u'closed', u'neither', u'bed', u'opening', u'hurrying', u'key', u'puzzled', u'staring', u'shingle', u'taking', u'doorway', u'figures', u'swallow', u'otherwise', u'walk', u'laugh', u'table', u'.--', u'seaography', u'thanked', u'immense', u'poured', u'slowly', u'treat', u'certain', u'curtain', u'proposal', u'kitchen', u'remedies', u'shoulders', u'am', u'farmer', u'neighbour', u'latitude', u'finished', u'smoking', u'general', u'present', u'holiday', u'appearance', u'examine', u'will', u'riper', u'wild', u'advisable', u'instantly', u've', u'almost', u'vi', u'jelly', u'helped', u'against', u'partner', u'sits', u'tumbled', u'denial', u')', u'began', u'cross', u'brightened', u'strange', u'tumbling', u'digging', u'largest', u'party', u'glaring', u'twelfth', u'difficult', u'elbows', u'spell', u'drink', u'disagree', u'effect', u'beast', u'introduce', u'sisters', u'collar', u'cheshire', u'off', u'nevertheless', u'dinah', u'well', u'fighting', u'thought', u'--"\'', u'position', u'raving', u'drawing', u'usual', u'lest', u'taller', u'barking', u'cried', u'less', u'ambition', u'fancying', u'cries', u'distant', u'parchment', u'tight', u'sky', u'reasons', u'book', u'adoption', u'wet', u'earnestly', u'ought', u'kick', u'raven', u'ledge', u'whispers', u'five', u'know', u'knot', u'desk', u'immediately', u'audibly', u'flamingo', u'ahem', u'lost', u'sizes', u'crawled', u'lose', u'become', u'works', u'soft', u'likes', u'because', u'authority', u'hair', u'choosing', u'proper', u'home', u'happens', u'est', u'esq', u'avoid', u'kettle', u'leap', u'does', u'passion', u'saucepan', u'belt', u'chains', u'?', u'pepper', u'noise', u'reaching', u'contradicted', u'isn', u'choked', u'crust', u'trials', u'gained', u'sister', u'ashamed', u'carried', u'getting', u'tray', u'carrier', u'tongue', u'introduced', u'swimming', u'turtle', u'!"', u'letters', u"!'", u'screamed', u'guard', u'promise', u'tiny', u'quarrelling', u'custard', u'knuckles', u'ridge', u'rushed', u'rightly', u'*', u'noticed', u'spread', u'startled', u'powdered', u'fountains', u'repeated', u'hm', u'contemptuously', u'highest', u'."\'', u'eat', u'he', u'hearthrug', u'wise', u'places', u'!"\'', u'whether', u'wish', u'scroll', u'variations', u'signed', u'placed', u'below', u'woke', u'cake', u'piece', u'minutes', u'stirring', u'diligently', u'rabbits', u'whisper', u'pie', u'pig', u'twist', u'tempered', u'--(', u'ink', u"--'", u'trotting', u'happen', u'--"', u'dressed', u'lately', u'other', u'branch', u'suppress', u'hippopotamus', u'conclusion', u'giddy', u'repeat', u'star', u'muchness', u'stay', u'refreshments', u'chance', u'teacups', u'friends', u'grunted', u'--]', u'yelp', u'tinkling', u'lasted', u'rule', u'pictured', u'extras', u'elsie', u'understand', u'trims', u'baked'])

Using Statistics


In [8]:
fdist1 = nltk.FreqDist(alice_words)

In [9]:
fdist1.tabulate(20) #the top 20 most frequently seen words in this corpus


   ,    '  the  and    .   to    a   it  she    i   of said  you alice   ,'   in  was that   !'   as 
1993 1731 1642  872  764  729  632  595  553  543  514  462  411  398  397  369  357  315  278  263 

In [10]:
fdist1['rabbit']


Out[10]:
51

In [11]:
%pylab inline 
fdist1.plot(40,cumulative=True)


Populating the interactive namespace from numpy and matplotlib

In [12]:
%pylab inline
fdist1.plot(200,cumulative=True)


Populating the interactive namespace from numpy and matplotlib

In [13]:
for token in fdist1:
    if fdist1[token] < 60 and fdist1[token] > 50:
        print fdist1[token], '\t', token


51 	here
58 	my
51 	much
52 	just
56 	hatter
55 	gryphon
55 	quite
53 	think
51 	first
56 	way
51 	say
57 	its
54 	are
51 	some
59 	by
57 	an
56 	mock
51 	rabbit
57 	ll
52 	their
58 	began
59 	turtle
51 	--'

In [14]:
alice_bigrams = nltk.bigrams(alice_words)
fdist2 = nltk.FreqDist(alice_bigrams)
stopwords = ['!','.',',',';',"'",",'","!'","?'","*",":",'a','-','"','$','the','and','i','was','my','a','for','be','to','is','it']
for k,v in fdist2.items():
    if k[0] not in stopwords and k[1] not in stopwords and v > 25:
        print v,k


48 (u'went', u'on')
32 (u'that', u'she')
29 (u'she', u'went')
60 (u'she', u'had')
31 (u'she', u'could')
45 (u'you', u'know')
115 (u'said', u'alice')
61 (u'as', u'she')
26 (u'if', u'you')
56 (u'mock', u'turtle')
34 (u'she', u'said')
31 (u'march', u'hare')
28 (u'did', u'not')
37 (u'out', u'of')
26 (u'thought', u'alice')
29 (u'so', u'she')

Using NLTK's Text Object


In [15]:
alice = nltk.Text(alice_words)

In [16]:
alice.count('turtle')


Out[16]:
59

In [17]:
alice.concordance('turtle')


Displaying 25 of 59 matches:
to the game . chapter ix . the mock turtle ' s story ' you can ' t think how g
to alice , ' have you seen the mock turtle yet ?' ' no ,' said alice . ' i don
. ' i don ' t even know what a mock turtle is .' ' it ' s the thing mock turtl
urtle is .' ' it ' s the thing mock turtle soup is made from ,' said the queen
ake this young lady to see the mock turtle , and to hear his history . i must 
t gone far before they saw the mock turtle in the distance , sitting sad and l
e on !' so they went up to the mock turtle , who looked at them with large eye
i ' ll tell it her ,' said the mock turtle in a deep , hollow tone : ' sit dow
patiently . ' once ,' said the mock turtle at last , with a deep sigh , ' i wa
, with a deep sigh , ' i was a real turtle .' these words were followed by a v
 constant heavy sobbing of the mock turtle . alice was very nearly getting up 
. ' when we were little ,' the mock turtle went on at last , more calmly , tho
 in the sea . the master was an old turtle -- we used to call him tortoise --'
cause he taught us ,' said the mock turtle angrily : ' really you are very dul
t last the gryphon said to the mock turtle , ' drive on , old fellow ! don ' t
 alice . ' you did ,' said the mock turtle . ' hold your tongue !' added the g
 alice could speak again . the mock turtle went on . ' we had the best of educ
 .' ' with extras ?' asked the mock turtle a little anxiously . ' yes ,' said 
c .' ' and washing ?' said the mock turtle . ' certainly not !' said alice ind
really good school ,' said the mock turtle in a tone of great relief . ' now a
afford to learn it .' said the mock turtle with a sigh . ' i only took the reg
 course , to begin with ,' the mock turtle replied ; ' and then the different 
bout it , so she turned to the mock turtle , and said ' what else had you to l
ell , there was mystery ,' the mock turtle replied , counting off the subjects
 ' t show it you myself ,' the mock turtle said : ' i ' m too stiff . and the 

In [18]:
alice.collocations()


mock turtle; said alice; march hare; white rabbit; thought alice;
beautiful soup; golden key; good deal; kid gloves; mary ann; yer
honour; three gardeners; play croquet; white kid; lobster quadrille;
ootiful soo; great hurry; poor little; poor alice; father william

In [19]:
%pylab inline 
alice.dispersion_plot(['alice','rabbit','turtle','queen'])


Populating the interactive namespace from numpy and matplotlib

You Try It

  1. Using the Toyota Complaints Text
  2. What are the most frequent bigrams?
  3. Can you find a notable trend?

In [ ]: