Skip to main content
v2026.11,986 entries · CC-BY 4.0

Text Mining: Definition, Pipeline and a Worked tf-idf Example

Text mining defined for researchers: how it differs from search and data mining, the pipeline, and a tf-idf example worked step by step.

Written and maintained by CASRAI Editorial Board

Published

On this page

Text mining is the computational discovery of new information from natural-language text: software turns a collection of documents into counts, weights or categories that a researcher can then analyse statistically. In research practice it usually means a short pipeline (collect documents, split them into tokens, represent each document as numbers, then model or compare the numbers), with every step documented and validated against a close reading of the text.

What is text mining? Definition and how it differs from search and data mining

Marti Hearst defines text mining as “the discovery by computer of new, previously unknown information” drawn from text (Hearst, 2003). Her distinction is useful for researchers. Search looks for something that is “already known and has been written by someone else”, whereas text mining targets information that “no one yet knows and so could not have yet written down”. Data mining, by contrast, finds patterns in structured databases, while text mining extracts patterns “from natural language text rather than from structured databases of facts”. In her account the output is new facts or hypotheses, which are then tested by conventional experimentation.

For social scientists the practical reading is this: a keyword query retrieves documents you already know how to describe, while text mining summarises or structures a corpus too large to read in full. Grimmer and Stewart (2013) make the same case for political texts: automated text analysis “substantially reduces the costs of analyzing large collections of text”, but the methods are “no substitute for careful thought and close reading and require extensive and problem-specific validation.”

It sits next to several neighbouring methods covered on this site. Content analysis is the human-coding tradition that text mining partly automates, sentiment analysis is one common text-mining task, and computational social science is the wider field in which large-scale text analysis is used. See also the sociology and anthropology discipline hub.

The text mining pipeline in five steps

1. Assemble the corpus

A corpus is the set of documents you analyse, and the unit of analysis (a tweet, an interview transcript, a paragraph, a whole report) is a design decision made before any software runs. Record where each document came from and how it was selected, because every later result depends on that choice.

2. Tokenize

Tokenization splits text into tokens. Silge and Robinson define a token as “a meaningful unit of text, most often a word, that we are interested in using for further analysis”, and describe the tidy text format as “a table with one-token-per-row”. Their tidytext function unnest_tokens(output_col, input_col) uses single words by default, strips punctuation and lowercases the text.

3. Represent documents as numbers

The common representation is the bag of words: each document becomes a row of word counts in a document-term matrix. In the scikit-learn documentation, documents are described “by word occurrences while completely ignoring the relative position information”. Matrix values are typically raw counts or tf-idf weights (Silge and Robinson, ch. 1).

4. Weight, model or compare

Weighting (below), clustering, topic models and classifiers all operate on the matrix. The choice of method follows the research question, not the other way round.

5. Validate against close reading

Because output depends on every upstream choice, read a sample of the documents behind each result and check that the numbers mean what you claim. This is the single most repeated recommendation in the methodological literature cited here.

Text mining formula: tf-idf with every symbol explained

There is no single formula for text mining, but term frequency-inverse document frequency (tf-idf) is the standard weighting step. It raises the weight of words that are frequent in one document and rare across the corpus. The scikit-learn documentation gives the inverse document frequency, with its default smoothing, as:

idf(t) = ln((1 + n) / (1 + df(t))) + 1

  • t: a term (token).
  • n: the number of documents in the corpus.
  • df(t): the number of documents that contain the term t at least once.
  • ln: the natural logarithm.

The weight of a term in a document is its count in that document multiplied by idf(t), and with scikit-learn’s defaults (use_idf=True, norm='l2') each document’s row is then divided by its Euclidean length. Without smoothing (smooth_idf=False) the formula is idf(t) = ln(n / df(t)) + 1. The data table below compares the two versions for a four-document corpus.

Worked example: a tf-idf document-term matrix by hand

This is an illustrative composite corpus written for this page, not data from any study. It has n = 4 short documents:

  • D1: survey responses show trust in local government
  • D2: interview transcripts show trust in local police
  • D3: survey responses show low trust in national media
  • D4: police reports describe local crime trends

Counting document frequencies (scikit-learn’s default tokenizer keeps words of two or more letters, so “in” counts): trust appears in 3 documents, show in 3, local in 3, in in 3, police in 2, interview in 1, transcripts in 1. Take document D2 and compute smoothed idf for each of its terms:

  • idf(trust) = ln(5/4) + 1 = 0.2231 + 1 = 1.2231 (the same value applies to show, in and local, each with df = 3)
  • idf(police) = ln(5/3) + 1 = 0.5108 + 1 = 1.5108
  • idf(interview) = ln(5/2) + 1 = 0.9163 + 1 = 1.9163 (the same value applies to transcripts)
Term in D2 Count df idf Count × idf After L2 normalisation
in 1 3 1.2231 1.2231 0.310
interview 1 1 1.9163 1.9163 0.485
local 1 3 1.2231 1.2231 0.310
police 1 2 1.5108 1.5108 0.382
show 1 3 1.2231 1.2231 0.310
transcripts 1 1 1.9163 1.9163 0.485
trust 1 3 1.2231 1.2231 0.310

The row’s Euclidean length is the square root of 4 × 1.2231² + 2 × 1.9163² + 1.5108² = 5.984 + 7.344 + 2.283 = 15.611, which is 3.951. Dividing each weight by 3.951 gives the last column (for example, 1.9163 / 3.951 = 0.485). The two words that appear only in D2 (interview, transcripts) now carry the most weight, because they best distinguish D2 from the rest of the corpus.

Interpreting tf-idf weights

A tf-idf weight describes how distinctive a term is for a document relative to this particular corpus. It is not a measure of importance in the real world, and it changes whenever the corpus changes.

What you see Reading
High weight The term is frequent in this document and appears in few other documents of the corpus.
Low weight The term is rare in the document, or appears in many documents (with smoothed idf the lowest possible idf is 1, reached when every document contains the term).
Same term, different weight in another corpus Expected: df(t) and n are properties of the corpus, so idf changes when documents are added or removed.
Weights close to 0 after normalisation The term contributes little to the document’s direction in the matrix; a long document spreads its unit length over many terms.

The data table below the guide lists the idf values for every possible document frequency in a four-document corpus, which shows how quickly the weight falls as a term becomes common.

Assumptions and common mistakes

  • Treating word order as irrelevant without saying so. The bag-of-words representation ignores position, so “trust in police” and “police in trust” produce identical rows. State this limit when you interpret results.
  • Letting software defaults decide silently. Tokenization rules, lowercasing, minimum token length and stop-word removal all change the matrix. Report the settings you used.
  • Treating output as findings without validation. Grimmer and Stewart (2013) stress that automated methods require extensive and problem-specific validation, which in practice means reading documents behind each result.
  • Confusing search with mining. Counting how often a known phrase occurs is closer to search; Hearst’s definition of text mining is about surfacing information not already written down.
  • Comparing tf-idf values across corpora. Because idf depends on n and df, weights from two corpora are not on a shared scale.
  • Ignoring research ethics and data governance. Text collected from people (interviews, posts) carries consent and privacy obligations that apply to the analysis as much as to collection. For validated human coding to compare against, see Cohen’s kappa.

How to report a text mining analysis

The following is editorial guidance for methods sections, not a rule from a style manual. A reader should be able to reproduce your matrix from your description, so state: the corpus and how documents were selected; the unit of analysis; the software and its version; tokenization and preprocessing choices; the weighting scheme and any smoothing or normalisation; and what validation you performed.

An illustrative methods sentence: “Interview transcripts (N = 4 documents) were tokenized into lowercase single words of at least two letters, represented as a document-term matrix, and weighted with smoothed tf-idf and L2 normalisation using scikit-learn’s TfidfVectorizer; the highest-weighted terms for each transcript were checked against the transcript text.” Cite the software and the methodological sources you relied on in your discipline’s reference style, and where results feed a wider computational reproducibility claim, share the code and corpus where consent permits.

How to do text mining in Excel, R or Python

Python (scikit-learn)

The scikit-learn documentation states that TfidfVectorizer combines CountVectorizer and TfidfTransformer, so one call produces the matrix from the worked example:

from sklearn.feature_extraction.text import TfidfVectorizer
docs = ["survey responses show trust in local government",
        "interview transcripts show trust in local police",
        "survey responses show low trust in national media",
        "police reports describe local crime trends"]
vec = TfidfVectorizer()          # smooth_idf=True, norm='l2' by default
X = vec.fit_transform(docs)      # sparse matrix, 4 rows
print(vec.get_feature_names_out())
print(X[1].toarray().round(3))   # row for D2

Under the formulas above, the D2 row should contain the values in the worked-example table.

R (tidytext)

library(dplyr); library(tidytext)
docs = tibble(doc = paste0("D", 1:4), text = c(
  "survey responses show trust in local government",
  "interview transcripts show trust in local police",
  "survey responses show low trust in national media",
  "police reports describe local crime trends"))
docs %>% unnest_tokens(word, text) %>% count(doc, word)

This produces the one-token-per-row counts that Silge and Robinson describe; chapter 3 of their book covers tf-idf on top of such counts.

Excel

For a small corpus with one document per cell in A2:A5, the smoothed idf of a word can be computed as =LN((1+COUNTA(A2:A5))/(1+COUNTIF(A2:A5,"*trust*")))+1, which returns 1.2231 for “trust”. COUNTIF with wildcards matches substrings (so “*in*” would also match “interview”), which makes Excel suitable only for checking worked examples, not for real corpora.

Frequently asked questions

What is the difference between text mining and data mining?

Data mining finds patterns in structured databases, while text mining extracts patterns from natural language text (Hearst, 2003). The text must first be converted into a structured representation, such as a document-term matrix.

No. Search finds information that already exists and was written by someone; text mining aims at previously unknown information (Hearst, 2003).

Is text mining the same as content analysis?

They overlap. Content analysis traditionally relies on human coders, while Grimmer and Stewart (2013) discuss automatic content analysis methods for political texts. Automated results still need validation by close reading.

What does tf-idf measure?

It weights a word by how often it occurs in a document and how few documents of the corpus contain it, so distinctive words score higher than common ones.

Do I need to code to do text mining?

The examples above use Python and R, which are the tools covered by the sources read for this page. A spreadsheet can reproduce small worked examples but not real corpora.

Sources

  • Hearst, M. (2003, October 17). What is text mining? UC Berkeley School of Information. https://people.ischool.berkeley.edu/~hearst/text-mining.html (checked 2026-11-14)
  • Grimmer, J., and Stewart, B. M. (2013). Text as data: The promise and pitfalls of automatic content analysis methods for political texts. Political Analysis, 21(3), 267-297. https://doi.org/10.1093/pan/mps028 (checked 2026-11-14)
  • Silge, J., and Robinson, D. Text mining with R, chapter 1: The tidy text format. https://www.tidytextmining.com/tidytext (checked 2026-11-14)
  • scikit-learn user guide, Text feature extraction. https://scikit-learn.org/stable/modules/feature_extraction.html (checked 2026-11-14)

Data: Inverse document frequency (idf) by document frequency in a four-document corpus: smoothed vs unsmoothed

Computed from the two idf formulas in the scikit-learn text feature extraction guide for a corpus of n = 4 documents, showing how the weight of a term falls as it appears in more documents. Values rounded to four decimals.

Inverse document frequency (idf) by document frequency in a four-document corpus: smoothed vs unsmoothed
Document frequency casedf(t) (documents)idf smoothed (smooth_idf=True)idf unsmoothed (smooth_idf=False)
Term appears in 1 of 4 documents11.91632.3863
Term appears in 2 of 4 documents21.51081.6931
Term appears in 3 of 4 documents31.22311.2877
Term appears in 4 of 4 documents411

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Text Mining: Definition, Pipeline and a Worked tf-idf Example

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →