liveBook · Manning

Grammar

As explained in Natural Language Processing in Action, Second Edition

A grammar is a system of rules that specifies how valid expressions in a language are formed and interpreted.

Grammar is the system of rules that determines how tokens combine into expressions or statements that others can understand. It applies to both natural and programming languages, although programming languages use more rigid and unambiguous rules. section 1.1

Word order is part of grammar. Rearranging a short greeting may preserve its general intent, but rearranging a longer logical statement can destroy the relationships needed for a correct interpretation. section 1.7

Grammar matters because it:

  • Constrains which sequences of tokens count as valid expressions. section 1.1
  • Supports formal languages such as programming languages, SQL, and regular-expression patterns. section 1.1 section 1.7
  • Preserves logical relationships that bag-of-words representations discard. section 1.7

The language of locks

A combination lock accepts one meaningful sequence of symbols. Entering that sequence follows the lock’s grammar and produces a specific interpretation: releasing the hasp. Regular expressions use similarly strict patterns to recognize phrases such as a chatbot greeting and trigger an action. section 1.4.1

>>> from itertools import permutations

>>> [" ".join(combo) for combo in
...     permutations("Good morning Rosa!".split(), 3)
...     ]
['Good morning Rosa!',
 'Good Rosa! morning',
 'morning Good Rosa!',
 'morning Rosa! Good',
 'Rosa! Good morning',
 'Rosa! morning Good']

Generate permutations of “Good morning Rosa!” to see how word order changes while some short greetings retain similar intent. section 1.7

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Explains grammar through tokens, formal rules, and word-order effects rather than detailed parsing internals.
Examples
Uses programming-language tokens, permuted greetings, SQL-like queries, and a combination-lock analogy as concrete examples.
What you can do after
Apply grammar via regular expressions to recognize key phrases or commands and associate them with actions.
How it connects
Connects grammar to tokens, regular expressions, word order, syntax parsing, programming languages, and bag-of-words representations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.