Bigram Tokenization: How to Split Text into Word Pairs
Learn how bigram tokenization splits text into adjacent word pairs, which tokenizing choices change the result, and how to verify and save your output.
What bigram tokenization does to your text
Bigram tokenization turns a piece of text into a sequence of adjacent word pairs. First the text is split into tokens, which are the individual units you want to count, usually words. Then every token is paired with the one that follows it. A sentence with N tokens produces N − 1 bigrams, because each pair overlaps the next by one word.
The input is plain text: a sentence, a paragraph, a file or a whole collection of documents. The output is a list of ordered pairs, often with a count of how many times each pair appears. People use word pairs to find common phrases such as "New York" or "machine learning," to build simple language models that predict the next word, to compare writing styles, and to extract features for search or classification.
The term "bigram" can also mean a pair of adjacent characters, as in "th" or "he." This guide covers word bigrams only.
The pairing step is mechanical. The decisions that change your result happen during tokenization: what counts as a word, whether case matters, what happens to punctuation, and whether pairs may cross sentence boundaries. The rest of this guide walks through those decisions in order.
A before-and-after example
Illustrative input (one line, ordinary spaces, ending with a period):
The cat sat on the mat.
If you split only on spaces and keep everything else, you get six tokens: "The", "cat", "sat", "on", "the", "mat." The five bigrams are:
(The, cat)
(cat, sat)
(sat, on)
(on, the)
(the, mat.)
Two details in this output often surprise people. "The" and "the" are treated as different words, and the period stays attached to "mat." If you lowercase the text and strip punctuation first, the last pair becomes (the, mat), and (on, the) and (The, cat) both use the same lowercase "the." Neither version is wrong. Decide which one you need before you count anything.
Decisions to make before you split
| Decision | Options | Effect on bigrams |
| What counts as a token | Whitespace-separated chunks; runs of letters and digits; a library or language-specific tokenizer | Determines whether "mat." and "mat" match, and whether "don't" stays one token or becomes two |
| Case | Keep as written; lowercase; Unicode case folding | Keeping case separates "The cat" from "the cat"; folding merges them |
| Punctuation | Keep attached; keep as separate tokens; discard | Separate punctuation tokens create pairs like (mat, .); discarding them removes those pairs |
| Sentence boundaries | Pair across the whole text; pair within each sentence; add start and end markers | Pairing across the text creates pairs like (mat, The) that span two sentences |
| Unicode normalization | Leave as is; normalize to a single form such as NFC | Without normalization, visually identical words can be stored as different character sequences and fail to match |
Start and end markers, often written <s> and </s>, are a common convention in language modeling. Adding them to "the cat sat" yields (<s>, the) and (sat, </s>), which record which words tend to begin and end sentences. Add them only if your downstream use needs that information.
How to produce bigrams step by step in Python
Python is used here because its standard library covers every step without extra installs. The code below is an illustrative example: read it, adapt it, and run it against your own text. It is not presented as verified output for your data.
Prerequisites: Python 3, and a plain-text input file whose encoding you know. The examples assume UTF-8. If your file uses another encoding, change the encoding argument, or accented and non-Latin characters may decode incorrectly or raise an error.
Step 1: Read and normalize the text
import unicodedata
with open("input.txt", encoding="utf-8") as f:
text = f.read()
text = unicodedata.normalize("NFC", text)
text = text.casefold()
NFC normalization makes a precomposed "é" and an "e" followed by a combining accent compare as equal. casefold() is a stricter form of lowercasing intended for caseless matching; for example, it turns the German "ß" into "ss." If you only want ordinary lowercase, use lower(). If case carries meaning in your analysis, such as distinguishing "Apple" the company from "apple" the fruit, skip this line.
Step 2: Split the text into word tokens
import re
WORD = re.compile(r"\w+(?:['’]\w+)*")
tokens = WORD.findall(text)
In Python 3, \w matches Unicode letters, digits and the underscore, so words like "café" and "naïve" stay whole. The optional group keeps contractions such as "don't" or "it’s" together, whether the text uses a straight apostrophe (') or a curly one (’). Punctuation and whitespace are dropped. Hyphenated words like "well-known" become two tokens with this pattern; add the hyphen to the character set if you want them kept together.
If you would rather split purely on whitespace, use text.split() with no arguments. It treats any run of whitespace, including tabs and Windows-style CRLF line endings, as one separator and never yields empty tokens. Punctuation stays attached to neighboring words.
Step 3: Pair each token with the next one
bigrams = list(zip(tokens, tokens[1:]))
zip stops at the shorter of its two inputs. That is why the final token does not get a pair with nothing, and why a text with one token or none yields an empty list rather than an error.
Step 4 (optional): Keep pairs inside sentence boundaries
Steps 2 and 3 treat the whole text as one stream, so the last word of one sentence pairs with the first word of the next. To prevent that, split into sentences first and pair within each one:
sentences = re.split(r"[.!?]+", text)
bigrams = []
for sentence in sentences:
toks = WORD.findall(sentence)
bigrams.extend(zip(toks, toks[1:]))
This sentence splitter is deliberately simple. It will break on abbreviations such as "Dr." and on decimal numbers such as "3.5." For text full of those, use a dedicated sentence tokenizer from an NLP library and check its documentation for how it handles abbreviations in your language.
Step 5: Count the pairs and save them to a new file
from collections import Counter
counts = Counter(bigrams)
with open("bigrams.tsv", "w", encoding="utf-8", newline="\n") as out:
for (first, second), n in counts.most_common():
out.write(f"{first}\t{second}\t{n}\n")
Tab-separated output keeps the two words unambiguous even if a token contains a space or comma. Setting newline="\n" writes Unix-style line endings on every platform; remove it if a Windows tool downstream expects CRLF.
Worked example with a result check
Illustrative input:
The cat sat on the mat. The cat slept.
After casefolding and running Step 2, the tokens are: the, cat, sat, on, the, mat, the, cat, slept. That is nine tokens. Pairing across the whole text (Step 3) gives eight bigrams:
(the, cat)
(cat, sat)
(sat, on)
(on, the)
(the, mat)
(mat, the)
(the, cat)
(cat, slept)
Counting them gives (the, cat) twice and every other pair once. With the sentence-aware version from Step 4, (mat, the) disappears: the first sentence has six tokens and five pairs, the second has three tokens and two pairs, for seven bigrams in total.
Checks you can run on any output:
- Count check: for a single stream, the number of bigrams should equal the number of tokens minus one, or zero if there are fewer than two tokens. For sentence-aware output, add up max(tokens − 1, 0) for each sentence.
- Chain check: in single-stream output, the second word of each pair should equal the first word of the next pair.
- Spot check: pick one sentence from the source and confirm its pairs by hand.
- Empty-token check: no pair should contain an empty string. If one does, your splitting step is producing blanks, which often happens when splitting on a single space instead of on runs of whitespace.
- Case and punctuation check: search the output for capital letters or punctuation marks you meant to remove.
assert len(bigrams) == max(len(tokens) - 1, 0)
assert all(a and b for a, b in bigrams)
The first assertion applies only to the single-stream version from Step 3.
A quick command-line alternative
If you only need pairs and don't want to write a script, awk can produce single-stream bigrams from whitespace-separated words. This is an illustrative one-liner, not tested against your data:
awk '{ for (i = 1; i <= NF; i++) { if (prev != "") print prev "\t" $i; prev = $i } }' input.txt > bigrams.txt
It carries the last word of each line over to the first word of the next line, so pairs cross line and sentence boundaries. It does not lowercase or strip punctuation. Two caveats apply. Files with Windows CRLF line endings leave a carriage return attached to the last word of each line, so convert the line endings first. And whether characters such as the non-breaking space count as separators depends on your awk implementation and locale.
Protecting your original text
Bigram extraction reads your text and does not need to change it. Write results to a new file and keep the source untouched. In a shell, never redirect output to the same file you are reading, as in awk '...' input.txt > input.txt. The shell truncates the file before the command reads it, and the original content is lost. If you normalize or clean the text before tokenizing, save the cleaned version under a new name, so you can trace any odd bigram back to the original wording.
Known gaps and when this approach falls short
- Languages written without spaces between words, such as Chinese, Japanese and Thai, need a language-specific word segmenter before pairing. The \w+ pattern above would treat a whole run of characters as a single token. No specific segmenter is recommended here, because none was evaluated for this guide.
- The regular expression and the sentence splitter are general-purpose starting points. They have not been checked against specialized text such as code, URLs, chemical names or social media handles.
- No performance figures are given for large files. If memory becomes a problem, process the file line by line or sentence by sentence and update the Counter incrementally instead of reading everything at once.
- NLP libraries such as NLTK provide their own tokenizers and bigram helpers. Their rules for punctuation, contractions and sentence splitting differ from the patterns shown here, so compare outputs on a sample before switching.