Natural Language Processing with Python – Free Online Book (Bird, Klein, Loper) BS AI / BSCS

BS Artificial Intelligence and BSCS students can read Natural Language Processing with Python, known as the NLTK Book, by Steven Bird, Ewan Klein and Edward Loper, free on its official site. It teaches NLP by doing: you write short Python programs with the NLTK library to tokenize text, tag parts of speech, classify documents, chunk phrases, parse sentences and build simple meaning representations. There is no PDF on the official site. The free edition is the online (HTML) book, updated for Python 3 and NLTK 3.0, so this page links to it.

Read it knowing which era it comes from. The print edition was published by O’Reilly Media in 2009, and the book does not cover neural networks, word embeddings or transformers. What it does teach is the vocabulary every NLP course still starts with, namely tokens, corpora, taggers, classifiers, grammars and logic, through code you can run. The licence is CC BY-NC-ND 3.0 US, which allows non-commercial sharing but no changes, so this page contains only original study notes: our own chapter summaries, key points and practice questions, with nothing copied from the book.

Book Overview

CourseNatural Language Processing / Computational Linguistics
Degree ProgramsBS Artificial Intelligence, BSCS
LevelUniversity / Undergraduate (introductory to intermediate)
EditionWeb edition updated for Python 3 and NLTK 3.0; print edition by O’Reilly Media, 2009
AuthorsSteven Bird, Ewan Klein and Edward Loper
Publisher (print)O’Reilly Media, ISBN 978-0-596-51649-9
StructurePreface and 12 chapters, plus bibliography and term index
Programming LanguagePython 3 with the NLTK library
ExercisesGraded exercises at the end of Chapters 1 to 11
LanguageEnglish
LicenseCC BY-NC-ND 3.0 US — Model: Link-only
FormatFree online book (HTML); no PDF on the official site

Chapter List

Chapter 1: Language Processing and Python

Difficulty: Easy · Key topics: Python basics, NLTK sample texts, concordance, tokens and types, lexical diversity, frequency distributions, collocations, bigrams, word sense disambiguation

Chapter 1 alternates between two styles: “computing with language” sections that set a small linguistic task, and “closer look at Python” sections that explain the code behind it. Using the sample texts loaded by from nltk.book import *, where text1 is Moby Dick, you search with concordance and similar, draw a dispersion plot, and count vocabulary. Lists, indexing, slicing, variables and strings are introduced as they are needed, followed by frequency distributions, long-word selection, collocations, bigrams, and if and for statements. The chapter closes with a tour of harder problems: word sense disambiguation, pronoun resolution, machine translation, dialog systems and textual entailment.

Key Points:

  • A token is one occurrence of a word; a type is a distinct word form. len(text) counts tokens and len(set(text)) counts types.
  • sorted(set(t)) gives the vocabulary of a text t.
  • text.concordance("word") shows every occurrence in context; text.similar("word") lists words used in similar contexts.
  • Lexical diversity is the ratio len(set(text)) / len(text).
  • A collocation is a word sequence that occurs together unusually often, such as “red wine”; bigrams() turns a list into word pairs.
  • A for or if line must end with a colon and be followed by an indented block.

Practice Tip: Run text1.similar("monstrous") and then text2.similar("monstrous"). The two lists differ, and that difference between Melville and Austen is the whole point of the chapter: meaning follows context.

Common Mistake: Typing bigrams([...]) and expecting a printed list. In Python 3 it returns a generator, so wrap it in list().

Important Questions:

  • What is the difference between a word token and a word type? A token is a particular appearance of a word in a text; a type is the unique form. “The cat saw the dog” has five tokens but four types.
  • How do you measure the lexical diversity of a text? Divide the number of distinct words by the total number of words: len(set(text)) / len(text). A higher ratio means less repetition.

Chapter 2: Accessing Text Corpora and Lexical Resources

Difficulty: Easy · Key topics: Gutenberg and Brown corpora, Reuters, inaugural addresses, conditional frequency distributions, functions and modules, stopwords, pronouncing dictionary, WordNet

Chapter 2 introduces the standard corpora that ship with NLTK: a Gutenberg selection, web and chat text, the genre-labelled Brown Corpus, the Reuters news collection and the Inaugural Address Corpus, then annotated and non-English corpora and how to load your own. Conditional frequency distributions count words per genre or other condition, can be tabulated or plotted, and drive a bigram-based random text generator. A “more Python” section covers editing programs in a text editor, functions and modules. The second half moves to lexical resources: wordlist corpora such as stopwords and name lists, the CMU Pronouncing Dictionary, comparative wordlists, Toolbox lexicons, and WordNet with its synsets, hierarchy and similarity measures.

Key Points:

  • A text corpus is a large, structured collection of texts; nltk.corpus.brown is the Brown Corpus, organised by genre.
  • Corpus categories can overlap; one Reuters article can belong to several topics.
  • A conditional frequency distribution is a collection of frequency distributions, one per condition, for example one per genre.
  • Programs longer than a few lines belong in a .py file that you load with import.
  • Methods are called as x.funct(y); help(v) prints the documentation for any object.
  • WordNet groups words into synonym sets (synsets) linked by relations such as hypernym and hyponym.

Practice Tip: Build a ConditionalFreqDist over the Brown Corpus and tabulate the modal verbs can, could, may, might, must and will by genre. News and romance text give very different rows.

Common Mistake: Treating stopwords.words('english') as a universal list. It is one wordlist for one language, and removing it can also remove words that matter for your task.

Important Questions:

  • What is a conditional frequency distribution? A set of frequency distributions, each tied to a condition such as a genre or a language, so you can compare how word counts change between conditions.
  • What is a WordNet synset? A set of synonyms that share one meaning; synsets are connected into a network by relations such as hypernymy (more general) and hyponymy (more specific).

Chapter 3: Processing Raw Text

Difficulty: Medium · Key topics: reading files and URLs, HTML cleaning, Unicode, string operations, regular expressions, tokenization, stemming, lemmatization, segmentation

Chapter 3 shows how to bring your own text into Python: downloading an electronic book from a URL, stripping HTML, reading local files, and reading RSS feeds or binary formats. It reviews strings at the lowest level (indexing, slicing, joining, splitting), explains Unicode and encodings, then spends a long section on regular expressions for finding word pieces and stems. From there it normalises text with the Porter and Lancaster stemmers and the WordNet lemmatizer, and tokenizes with nltk.word_tokenize() and a regular-expression tokenizer. It ends with sentence and word segmentation and with turning lists back into formatted strings.

Key Points:

  • A raw text is one long string; the book then views a text as a list of tokens.
  • Read a web page with request.urlopen(url).read().decode('utf8'); web text usually needs its markup removed first.
  • Tokenization splits text into words and punctuation; whitespace splitting alone leaves punctuation attached.
  • Stemmers strip affixes by rules; a lemmatizer maps a word to its dictionary form, such as appeared to appear.
  • Use re.findall() after import re to find every substring that matches a pattern.
  • Write regular expressions as raw strings, r'...', because Python treats backslash escapes (for example \n) specially.

Practice Tip: Run both stemmers on the same sentence, for example nltk.PorterStemmer() and nltk.LancasterStemmer(). The book shows they disagree on words like lying, which teaches you to check a stemmer’s output before trusting it.

Common Mistake: Forgetting the r prefix on a regular expression. Without it, Python processes the backslashes first and the pattern silently matches the wrong thing.

Important Questions:

  • Why is tokenizing on whitespace not enough? It glues punctuation to words, so “word,” and “word” become different tokens. Tools such as word_tokenize() separate them.
  • What is the difference between stemming and lemmatization? A stemmer chops affixes using rules and may produce non-words; a lemmatizer returns a real dictionary form (the lemma) using a lexical resource.

Chapter 4: Writing Structured Programs

Difficulty: Medium · Key topics: object references, sequences, comprehensions, coding style, functions and scope, modules, debugging, recursion, dynamic programming, Python libraries

Chapter 4 is the book’s consolidation of Python itself, organised by language features rather than by NLP tasks. It explains assignment as object references, the difference between is and ==, and how strings, lists and tuples behave as sequences. It then compares procedural and declarative style, builds up functions (parameter passing, variable scope, docstrings, higher-order functions and named arguments), and covers modules, sources of error and defensive programming. Algorithm design follows, with recursion, space-time trade-offs and dynamic programming. The chapter ends with a quick tour of Matplotlib, NetworkX, csv and NumPy.

Key Points:

  • Assignment copies a reference, so after b = a a change to the list through a is visible through b.
  • is tests whether two names point to the same object; == tests whether two objects are equivalent.
  • Prefer a declarative style and enumerate() over hand-incremented loop counters.
  • Names defined inside a function are local unless declared global, so a function acts as a namespace.
  • Recursion solves a problem by calling the same function on a smaller piece.
  • Dynamic programming stores earlier results so they are never recomputed.

Practice Tip: Type in the book’s Sanskrit-meter example (counting the ways to combine short and long syllables) in its recursive form, then in its table-lookup form, and time both for a larger n. The speed gap is the clearest demonstration of dynamic programming you can run in five minutes.

Common Mistake: Assuming b = a makes a separate copy of a list. Both names refer to one list, so edits through either name show up in both.

Important Questions:

  • What is the difference between is and ==? == checks equal value; is checks that both names refer to the very same object in memory. The book compares this to the type-token distinction.
  • What is dynamic programming? An algorithm design technique that saves the results of sub-problems in a table or memo so each is computed only once; it is widely used in NLP.

Chapter 5: Categorizing and Tagging Words

Difficulty: Medium · Key topics: parts of speech, tagsets, tagged corpora, dictionaries, default and regular-expression taggers, n-gram taggers, backoff, evaluation, Brill tagging

Chapter 5 asks how a program can label every word with its part of speech. It starts with tagged corpora and a simplified tagset, then explores nouns, verbs, adjectives and adverbs in the tagged Brown Corpus. Python dictionaries (including default dictionaries) are introduced as the data structure for mapping words to properties. Automatic taggers are then built in steps: a default tagger, a regular-expression tagger, a lookup tagger, then unigram and n-gram taggers, combined through backoff and judged with a held-out test set. The chapter finishes with transformation-based (Brill) tagging and with how morphological, syntactic and semantic clues decide a word’s category.

Key Points:

  • Part-of-speech tagging assigns a tag such as NN (noun) or VB (verb) to each token, using a tagset.
  • Tagging is the second step of the usual NLP pipeline, right after tokenization.
  • A dictionary maps keys to values, for example freq['cat'] = 12, and is created with braces.
  • A default tagger that labels everything NN is correct for only about 13% of tokens on the book’s Brown sample, which makes it a useful baseline.
  • Backoff combines taggers: if a bigram tagger has no answer, fall back to a unigram tagger, then to a default.
  • For n-gram taggers with n above 3, the sparse data problem appears: most contexts are never seen in training.

Practice Tip: Chain a bigram tagger, a unigram tagger and a default tagger with backoff, train on one part of brown.tagged_sents() and evaluate on another. Seeing accuracy jump at each layer shows why backoff exists.

Common Mistake: Evaluating a tagger on the same sentences it was trained on. The score looks excellent and tells you nothing about unseen text.

Important Questions:

  • What is backoff in tagging? A way of combining models: when a specialised tagger (such as a bigram tagger) cannot tag a word in its context, it passes the word to a more general one (a unigram tagger, then a default tagger).
  • Why do we need separate training and test data? Testing on training data rewards memorisation. A held-out test set measures how the tagger behaves on text it has never seen.

Chapter 6: Learning to Classify Text

Difficulty: Medium · Key topics: supervised classification, feature extraction, document classification, sequence classification, evaluation metrics, decision trees, naive Bayes, maximum entropy

Chapter 6 turns tagging into a general machine-learning problem: pick features of the input, train a classifier on labelled data, and test it. It builds a gender classifier from names to show how feature choice and error analysis improve accuracy, then applies the same recipe to document classification (movie reviews), part-of-speech tagging with context, sequence classification, sentence segmentation, dialogue act types and textual entailment. A long section covers evaluation: test sets, accuracy, precision and recall, confusion matrices and cross-validation. It ends by explaining decision trees (with entropy and information gain), naive Bayes and maximum entropy classifiers, while skipping most of the mathematics.

Key Points:

  • A supervised classifier learns from labelled examples to predict the label of a new input from its features.
  • Split data into a training set, a dev-test set for tuning features, and a final test set used once.
  • Accuracy alone can mislead; precision, recall and a confusion matrix show which errors occur.
  • A decision tree is a learned flowchart; it is easy to read but handles interacting features poorly.
  • Naive Bayes lets every feature vote independently, which hurts when features are strongly correlated.
  • Maximum entropy classifiers fit feature weights by iterative optimisation and are the third classifier family covered.

Practice Tip: Rebuild the name-gender classifier, start with “last letter” as the only feature, and add one feature at a time while checking the dev-test accuracy. You will see exactly which features help and which add noise.

Common Mistake: Tuning features against the final test set. Once you do, the test result is optimistic; keep the dev-test set for tuning and touch the test set once.

Important Questions:

  • Why split data into training, dev-test and test sets? Training builds the model, dev-test guides feature choices, and the untouched test set gives an honest final score.
  • What is the weakness of naive Bayes? It assumes features are independent, so strongly correlated features get counted twice and can skew the decision.

Chapter 7: Extracting Information from Text

Difficulty: Medium · Key topics: information extraction, noun phrase chunking, tag patterns, chinking, IOB tags, CoNLL-2000, cascaded chunkers, named entity recognition, relation extraction

Chapter 7 shows how to pull structured facts out of unstructured text. It sketches a standard information extraction pipeline (sentence segmentation, tokenization, part-of-speech tagging, entity detection, relation detection) and then concentrates on chunking, which groups tagged words into non-overlapping phrases. You write chunk grammars with tag patterns and RegexpParser, remove material with chinking, represent chunks as IOB tags or trees, and evaluate on the CoNLL-2000 corpus. A classifier-based chunker is trained, chunkers are cascaded to build nested trees, and the chapter closes with named entity recognition and relation extraction.

Key Points:

  • Information extraction fills a database of entities and relations from raw text, so later questions can be answered from the table.
  • The pipeline order is segment, tokenize, tag, detect entities, then detect relations between nearby entities.
  • A chunker groups tagged tokens into flat, non-overlapping segments such as noun phrases.
  • Chunk rules are written as tag patterns, for example an optional determiner, any adjectives, then a noun.
  • IOB tags mark each token as inside, outside or at the beginning of a chunk, and are the standard storage format.
  • Common entity types are ORGANIZATION, PERSON, LOCATION, DATE, TIME, MONEY and GPE.

Practice Tip: Write a one-line noun phrase grammar for nltk.RegexpParser, run it on a tagged sentence of your own, and print the resulting tree. Then change one tag pattern and see which phrase breaks.

Common Mistake: Expecting a chunker to produce a full parse. Chunks are flat and cannot overlap, so nested structure needs cascaded chunkers or the parsers of Chapter 8.

Important Questions:

  • What is chunking? Segmenting and labelling multi-token sequences, usually noun phrases, on top of part-of-speech tags. It is a lightweight alternative to full parsing.
  • What are the main steps of an information extraction system? Segment, tokenize and tag the text; search it for named entities; then look at entities mentioned near one another to decide whether a relation holds.

Chapter 8: Analyzing Sentence Structure

Difficulty: Hard · Key topics: syntactic ambiguity, constituent structure, context-free grammar, recursion, recursive descent, shift-reduce, chart parsing, dependency grammar, treebanks, probabilistic grammar

Chapter 8 explains why n-gram methods are not enough for sentences: language has unbounded variety and pervasive ambiguity, as in the sentence about shooting an elephant in pajamas. It presents constituent structure and context-free grammars, shows how to write and test your own grammars with NLTK, and handles recursion. Parsing strategies come next: recursive descent, shift-reduce, the left-corner parser and well-formed substring tables (chart parsing). The chapter then covers dependency grammar and valency, grammar development with treebanks, pernicious ambiguity, and weighted (probabilistic) grammars.

Key Points:

  • A grammar is a compact description of a potentially infinite set of sentences; a grammar licenses a tree.
  • A context-free grammar uses productions such as NP -> Det N to rewrite a category into smaller parts.
  • Prepositional phrase attachment is the classic source of syntactic ambiguity.
  • A recursive descent parser works top-down and cannot handle left-recursive productions such as NP -> NP PP.
  • A shift-reduce parser works bottom-up with a stack and is not guaranteed to find a parse even when one exists.
  • A dependency grammar states which dependents each lexical head takes; a weighted grammar picks the most probable of many parses.

Practice Tip: Write the book’s small toy grammar as an nltk.CFG string, parse an ambiguous sentence with a chart parser and count the trees. Printing both trees shows ambiguity as something you can see, not just read about.

Common Mistake: Writing a left-recursive rule and then feeding it to the recursive descent parser. It loops forever instead of reporting a clear error.

Important Questions:

  • What is syntactic ambiguity? A sentence that has more than one valid syntactic analysis. “I shot an elephant in my pajamas” can attach the prepositional phrase to the shooting or to the elephant.
  • How does a recursive descent parser differ from a shift-reduce parser? The first expands from the start symbol downwards and tries to match the input; the second shifts words onto a stack and reduces them upwards using grammar productions.

Chapter 9: Building Feature-Based Grammars

Difficulty: Hard · Key topics: feature structures, agreement, unification, subsumption, subcategorization, auxiliary verbs, unbounded dependency, case government

Chapter 9 replaces the atomic category labels of Chapter 8 with feature structures, so that one symbol can carry information such as number, person or tense. It starts with grammatical features and syntactic agreement, then shows how attribute-value matrices, variables and constraints keep a grammar small. The formal part defines feature paths, re-entrancy, subsumption and unification, and shows how NLTK processes them. The final sections extend a feature grammar to verb subcategorization, heads, auxiliary verbs and inversion, unbounded dependency constructions and case in German.

Key Points:

  • Atomic categories multiply quickly (singular NP, plural NP, and so on); features capture such distinctions without a new symbol each time.
  • A feature value is atomic or complex, and Boolean values are written [+/- f].
  • Shared values are called re-entrant and are written with numeric indexes in attribute-value matrices.
  • Structure A subsumes structure B when all of A’s information is also in B.
  • Unification of two structures succeeds only if their information is compatible, and the result carries the combined information.
  • Feature structures give compact analyses of subcategorization, inversion, unbounded dependencies and case.

Practice Tip: Build two nltk.FeatStruct objects with one conflicting feature and try unify(). Seeing a conflict return None, and a compatible pair merge, makes unification concrete.

Common Mistake: Confusing subsumption with unification. Subsumption compares two structures; unification builds a third structure that contains both.

Important Questions:

  • Why use feature structures instead of atomic categories? They express fine-grained distinctions such as agreement without multiplying the number of category symbols and rules.
  • What is unification? The operation that merges two feature structures into one containing the information of both, succeeding only when they do not conflict.

Chapter 10: Analyzing the Meaning of Sentences

Difficulty: Hard · Key topics: semantics, propositional logic, first-order logic, model-theoretic truth, quantifier scope, lambda calculus, compositional semantics, discourse representation theory

Chapter 10 moves from structure to meaning. It opens with a small natural language interface to a database, then builds the logic needed: propositional logic, first-order logic with its syntax, theorem proving with Prover9, and truth in a model using valuations and variable assignments. Quantification and quantifier scope ambiguity are explained next. To turn English into logic automatically, the chapter adds the lambda calculus and treats a sem feature in a feature-based grammar, handling quantified noun phrases and transitive verbs. It closes with discourse semantics and Discourse Representation Theory.

Key Points:

  • First-order logic is expressive enough for much of natural language meaning and has efficient theorem provers.
  • A sentence is true or false relative to a model, which supplies a valuation for the non-logical constants.
  • An open expression has free variables and needs a variable assignment; a closed sentence has none.
  • Beta-reduction applies a lambda expression to an argument by substituting for the bound variable.
  • With two nested quantifiers, the outer one has wide scope, and English sentences are often ambiguous about this.
  • Meaning is built compositionally: the sem value of a phrase comes from the sem values of its parts.

Practice Tip: Use nltk.sem.Expression.fromstring() to parse a few first-order formulas and ask Prover9 whether a conclusion follows from two assumptions. Changing one assumption and re-running is the quickest way to feel what a proof does.

Common Mistake: Treating the order of quantifiers as cosmetic. “Every student read a book” has two readings, and swapping scope changes the truth conditions.

Important Questions:

  • Why is first-order logic used to represent meaning? It is flexible enough to represent many useful aspects of meaning, and automated theorem provers exist to reason with it.
  • What is the role of the lambda calculus? It lets us assemble meaning step by step: each word contributes a function, and beta-reduction applies functions to arguments to build the sentence meaning.

Chapter 11: Managing Linguistic Data

Difficulty: Medium · Key topics: corpus structure, TIMIT, corpus life-cycle, data conversion, annotation layers, XML, ElementTree, Toolbox lexicons, OLAC metadata

Chapter 11 is about the data side of NLP. It studies how the TIMIT speech corpus is structured, then names the two fundamental data types (annotated texts with a time structure, lexicons with a record structure) and follows the life-cycle of a corpus from collection through annotation and quality control to publication. Practical sections cover obtaining data from the web, word-processor files, spreadsheets and databases, converting formats, and special care for endangered languages. The book then teaches XML with ElementTree and Toolbox lexicon processing, and closes with OLAC metadata for describing and disseminating resources.

Key Points:

  • Annotated texts have a temporal structure; lexicons have a record structure.
  • A corpus life-cycle covers data collection, annotation, quality control and publication, and continues after publication.
  • A good corpus balances representativeness against having enough material from any single genre or source.
  • XML is a handy storage and exchange format but does not solve data-modeling problems by itself.
  • Toolbox format is widely used in language documentation, and Toolbox files can be converted to XML with a short program.
  • OLAC, the Open Language Archives Community, provides metadata so resources can be documented and found.

Practice Tip: Parse a small XML file with xml.etree.ElementTree, loop over its entries and print one field from each. The same loop pattern is what the chapter applies to a Toolbox lexicon.

Common Mistake: Assuming that converting a file to XML cleans it up. XML only stores structure; inconsistent or missing fields in the original data stay inconsistent.

Important Questions:

  • What are the stages in the life-cycle of a corpus? Data collection, annotation, quality control and publication, followed by continued modification and enrichment as research uses the corpus.
  • What is OLAC? The Open Language Archives Community, which defines metadata and infrastructure for documenting and discovering language resources.

Chapter 12: Afterword: Facing the Language Challenge

Difficulty: Easy · Key topics: symbolic vs statistical NLP, rationalism and empiricism, data-intensive methods, NLTK roadmap

The short closing chapter steps back from code. It argues that language is far richer than any single computational method, using a set of very different sample sentences. It traces how NLP grew out of formal language theory, symbolic logic and the principle of compositionality, and why speech recognition pushed the field toward data-intensive, machine-learning and evaluation-led methods. It then links these trends to the old debates between rationalism and empiricism and between realism and idealism, and ends with a roadmap of areas NLTK does not yet support well, from morphology to teaching materials.

Key Points:

  • Early NLP rested on formal language theory, symbolic logic and the principle of compositionality.
  • Speech recognition showed that systems learning from large data beat hand-written rules and moved the field to data-intensive methods.
  • Rationalism and empiricism reappear in NLP as the debate between introspection and corpus data.
  • Statistical and symbolic methods now inform each other; most advances involve a balance of the two.
  • The roadmap lists areas needing work, including phonology and morphology, lexical semantics, language generation and other languages.

Memory Tip: Remember the chapter as two arrows. Rules push meaning from theory into programs; data pulls patterns from corpora into models. Real systems use both.

Common Mistake: Reading the afterword as a prediction of today’s field. It describes the symbolic-versus-statistical balance of its time, before neural methods became dominant.

Important Questions:

  • Why did NLP move toward data-intensive methods? Systems that learned patterns from large bodies of speech data proved more accurate and robust than rule-based ones, and shared test data made progress measurable.
  • What is the principle of compositionality? The meaning of a complex expression is composed from the meanings of its parts and how they are combined, so meaning can be computed recursively.

How to Study This Book

Start with the Preface, which the book numbers as Chapter 0 and which is not a chapter block on this page. It states the audience, the software you need (Python 3.2 or later, NLTK 3.0 and the NLTK data package, with NumPy, Matplotlib, NetworkX and the Prover9 theorem prover as recommended or optional extras), and a table of reading goals for readers from arts and humanities versus science and engineering. Install and test your setup before Chapter 1, because every chapter assumes you can type examples into the interpreter.

Chapters 1 to 3 are the foundation and the only part of the book that needs no programming background. Do them in order and type every example. Chapter 2 introduces the corpora and WordNet that later chapters reuse, and Chapter 3 introduces the tokenizers, stemmers and regular expressions that nearly every project needs. If you already program in Python, skim Chapter 1 and read Chapter 3 carefully.

Chapter 4 is a Python consolidation chapter. Skip most of it if you are comfortable with functions, scope and sequences, but do read the sections on debugging and on recursion and dynamic programming, because the parsing material in Chapter 8 depends on those ideas.

Chapters 5 and 6 belong together: tagging in Chapter 5 is the example task that Chapter 6 generalises into supervised classification. If your course is about machine learning for text, read these two closely and then Chapter 7, which combines tokenizing, tagging and classifiers into chunkers and named entity recognition. Chapter 6 gives classic models (naive Bayes, decision trees, maximum entropy), not neural networks.

Chapters 8, 9 and 10 form a separate linguistics and logic track and must be read in that order: grammars and parsing, then feature structures and unification, then semantics with first-order logic and the lambda calculus. They are the hardest chapters and are often skipped in an applied course. A computational linguistics course will use them in full.

Chapter 11 is independent and best read after Chapter 2. It is useful for anyone who will build or document a dataset for a final-year project. Chapter 12 is a short essay with no exercises and can be read at any time.

Two practical warnings. First, the book targets NLTK 3.0, and its own notes in Chapters 3 and 4 describe stricter file and network access rules in NLTK 3.10 and later, so an example that opens a file outside your working folder or downloads a URL may fail on a current install. When an example errors, check the current NLTK documentation for the function’s present name or behaviour. Second, the book does not cover neural networks, word embeddings, transformers or large language models. Treat it as the foundation course and add a modern deep learning text for those topics.


Used In These Programs

This book is used for the Natural Language Processing course in: BS Artificial Intelligence · BS Computer Science. Browse all Natural Language Processing books, all Python books or all Computer Science books.

Who Should Read This

This book is written for students who want to learn NLP by writing programs: BS Artificial Intelligence and BSCS students in a first NLP, text mining or computational linguistics course, usually in the middle to later semesters. It also suits linguistics and humanities students who want to learn Python on text, since the Preface says the early chapters need no programming background. If your Python is shaky, work through Think Python first, or read Python for Everybody alongside Chapters 1 to 4. Chapters 8 to 10 lean on logic and set notation, which Discrete Mathematics: An Open Introduction covers well. It is not the right book if your syllabus is centred on deep learning, embeddings or large language models, and it is a tutorial rather than a reference, so use the NLTK documentation for exact function details.


Applicable Universities

This book is useful for students at Pakistani universities offering BS Artificial Intelligence, BS Computer Science and related NLP electives, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.

Official Copy of Natural Language Processing with Python

This book is free from its official site. There is no official PDF, so the legitimate free way to read it is the complete online edition. Click the button below to open the book on nltk.org, where you can read it chapter by chapter. The print edition is sold separately by O’Reilly Media.

→ Visit Official Page

FAQs

Is Natural Language Processing with Python free?

Yes. The authors publish the full web edition free at nltk.org/book under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License (CC BY-NC-ND 3.0 US). That licence lets you read and share the book with credit for non-commercial purposes, but not change it. The printed O’Reilly edition is sold separately.

Is there a PDF of this book?

There is no PDF on the official site. The free version is the online HTML edition, and that is what the button on this page opens. This site does not host or copy the book.

Which edition is this?

The print edition is O’Reilly Media, 2009. The online edition is the update for Python 3 and NLTK 3.0, and each chapter carries a copyright line for the authors dated 2019. The Preface says the code assumes Python 3.2 or later and NLTK 3.0.

How many chapters and exercises does it have?

The book has a Preface and 12 chapters, from Language Processing and Python to a closing Afterword, plus a bibliography and a term index. Chapters 1 to 11 end with graded exercises; Chapter 12 is a short essay without exercises.

Is it good for complete beginners?

For the first few chapters, yes. The Preface says Chapters 1 to 4 suit readers with no programming background, and it teaches Python as it goes. Chapters 8 to 10 on grammars, feature structures and logic are much harder and need patience, so take them slowly.

Is it still current in 2026, and does it cover transformers or LLMs?

The foundations still hold: tokenization, corpora, tagging, classifiers, chunking, grammars and semantics are standard NLP topics. But the book has no chapters on neural networks, word embeddings, transformers or large language models, and its code targets NLTK 3.0. Its own notes mention stricter file and network rules in NLTK 3.10 and later, so some examples may need small changes. Pair it with a modern deep learning NLP text.

Related Books

Natural Language Processing with Python remains one of the clearest hands-on introductions to NLP, as long as you treat it as the foundation course and not the whole field. Work through Chapters 1 to 7 at the keyboard, pick up Chapters 8 to 10 if your course covers parsing and semantics, and look elsewhere for neural methods. Browse more Computer Science books for the rest of your semester.

Natural Language Processing with Python by Steven Bird, Ewan Klein and Edward Loper. Print edition: O’Reilly Media, 2009. Copyright the authors, distributed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License (CC BY-NC-ND 3.0 US). Official source: https://www.nltk.org/book/. This page links to the official site and does not host or copy the book.

Leave a Comment