Skip to content

Describing a text column

Length, vocabulary, common phrases and sentiment, plus what a word list can and can't tell you.

Applied ~9 min8 steps

What runs in CodeSplash

You will be able to

  • Profile the length and content of a text column
  • Read top terms, and know why stop words matter
  • Explain the limits of lexicon sentiment

Read first

01

What's in the column?

Read

Text needs describing, like any other column. This set of product reviews has 59 texts, of which 1 is empty. The mean length is 8.2 words, and 1.7% contain a URL.

Those basics catch real problems: empty texts, templates pasted thousands of times, and personal data in a free-text field.

02

What will dominate?

Predict

Predict first

You count words in a corpus and leave every word in. What will top the list?

Words about the productsCommon English wordsBrand names
Reveal

The answer: Common English words

Common English words. With them left in, the top terms in this corpus are “the”, “and”, “in”, “with”, “rates”. With common words removed, the review data's top terms become “good”, “great”, “coffee”, “comfortable”, “nothing”.

03

Run it

In the app
Text explorationRecorded · Python and R agreeRecorded 2026-11-25 · 55 values compared
R

59 texts, 8.2 words on average; top words: “good”, “great”, “coffee”, “comfortable”, “nothing”; mean sentiment 0.19.

Texts
59
Mean words
8.153
Distinct tokens
282
Mean sentiment
0.1880

Plots

Most frequent wordsWhich words or phrases appear most in a text column, overall or by group?
View data
OccurrencesTerm
5good
5great
4coffee
4comfortable
4nothing
3best
3headphones
3love
3re
2absolutely
2brew
2carafe
2com
2cup
2cushioning
2example
2fantastic
2fine
2happy
2left
Distinctive words by productWhich words or phrases appear most in a text column, overall or by group?
View data
tf-idfproductTerm
0.0458coffee makercoffee
0.0229coffee makerbrew
0.0229coffee makercarafe
0.0229coffee makermorning
0.0114coffee makerannoying
0.0114coffee makerbuild
0.0114coffee makerburnt
0.0114coffee makercheap
0.0114coffee makerclean
0.0114coffee makerconstantly
0.0297headphonesheadphones
0.0198headphonescom
0.0198headphonesexample
0.0198headphonesmuch
0.0198headphonesnoise
0.0198headphonesreview
0.0198headphonessound
0.0198headphonesworst
0.0099headphonesamazing
0.0099headphonesanc
0.0234running shoescushioning
0.0234running shoeslook
0.0234running shoesperfect
0.0234running shoesruns
0.0234running shoesshoes
0.0234running shoessize
0.0117running shoesaverage
0.0117running shoesbeginners
0.0117running shoesblisters
0.0117running shoesbreak
Words per textHow is one numeric variable distributed?
View data
Words
8
10
8
9
8
6
12
11
9
9
7
12
8
7
7
9
8
8
8
9
9
8
9
9
8
7
8
7
10
9
10
10
9
6
9
10
6
5
0
9
6
10
7
12
9
6
7
7
9
9
9
5
6
10
9
10
7
7
5
Sentiment by productHow do groups compare in shape, summary and individual observations at once?
View data
productSentiment (compound)
headphones0.8912
headphones−0.4939
headphones0.7050
headphones0.5984
headphones−0.8545
headphones−0.0920
headphones0.8869
headphones0.2023
headphones0
headphones−0.6588
headphones0.7783
headphones−0.6124
headphones0.4226
headphones0
headphones0.8655
headphones−0.2732
headphones0.2960
headphones0.6249
headphones−0.3400
headphones0.7474
coffee maker0.6249
coffee maker0
coffee maker0.6808
coffee maker−0.0191
coffee maker0.5719
coffee maker−0.7074
coffee maker0.7184
coffee maker0.2023
coffee maker−0.3392
coffee maker0.8360
coffee maker0
coffee maker−0.5748
coffee maker−0.4019
coffee maker−0.1695
coffee maker0.4927
coffee maker−0.2500
coffee maker0.6908
coffee maker−0.4939
coffee maker0
coffee maker0.6696
running shoes0.8020
running shoes−0.5256
running shoes0.3716
running shoes0.7430
running shoes0.2263
running shoes−0.4023
running shoes0.5719
running shoes0.6249
running shoes0.7788
running shoes−0.2057
running shoes−0.5106
running shoes0.7430
running shoes−0.4404
running shoes0.2960
running shoes0
running shoes0.7713
running shoes0
running shoes0.7955
running shoes0.2263

Assumptions

  • English text — The stop list and VADER's lexicon are English; other languages need another tokenizer and sentiment model.
  • Personal data — 1 text(s) contain an e-mail address and 1 a URL; consider marking review text sensitive in the data dictionary.

Texts

MeasureValue
Texts59
Empty texts1
Characters per text (mean)47.542
Characters per text (median)48
Characters per text (max)77
Words per text (mean)8.153
Words per text (median)8
Words per text (max)12
Tokens (letter runs ≥ 2)462
Distinct tokens282
Type–token ratio0.6104
Share of texts with an e-mail address0.0169
Share of texts with a URL0.0169
Share of texts with a digit0.0847

Most frequent words

#TermOccurrencesTextsShare of texts
1good550.0847
2great550.0847
3coffee440.0678
4comfortable440.0678
5nothing430.0508
6best330.0508
7headphones330.0508
8love330.0508
9re330.0508
10absolutely220.0339
11brew220.0339
12carafe220.0339
13com220.0339
14cup220.0339
15cushioning220.0339
16example220.0339
17fantastic220.0339
18fine220.0339
19happy220.0339
20left220.0339

Common English words left out. Terms used in at least 2 text(s).

Characters

KindCountShare
Letters A–Z2,2410.7989
Digits140.0050
Spaces and line breaks4230.1508
ASCII punctuation1200.0428
Other ASCII (control)00
Non-ASCII (accents, symbols, emoji, other scripts)70.0025

By product

productTextsMean wordsMean sentimentPositiveNegative
coffee maker207.9000.12660.45000.3500
headphones208.6500.18470.55000.3500
running shoes197.8950.25610.63160.2632

Terms that set each product apart (tf-idf)

product#TermOccurrencestf-idf
coffee maker1coffee40.0458
coffee maker2brew20.0229
coffee maker3carafe20.0229
coffee maker4morning20.0229
coffee maker5annoying10.0114
coffee maker6build10.0114
coffee maker7burnt10.0114
coffee maker8cheap10.0114
coffee maker9clean10.0114
coffee maker10constantly10.0114
headphones1headphones30.0297
headphones2com20.0198
headphones3example20.0198
headphones4much20.0198
headphones5noise20.0198
headphones6review20.0198
headphones7sound20.0198
headphones8worst20.0198
headphones9amazing10.0099
headphones10anc10.0099
running shoes1cushioning20.0234
running shoes2look20.0234
running shoes3perfect20.0234
running shoes4runs20.0234
running shoes5shoes20.0234
running shoes6size20.0234
running shoes7average10.0117
running shoes8beginners10.0117
running shoes9blisters10.0117
running shoes10break10.0117

Each group's texts are one document: tf = share of the group's terms, idf = ln(groups / groups using the term).

  • 1 of 60 rows were left out because a value was missing.
  • 1 text(s) are empty.
  • Sentiment: VADER compound score (−1 to 1); positive ≥ 0.05, negative ≤ −0.05, neutral in between (Hutto & Gilbert 2014).
The exact R script · R R version 4.5.1 (2025-06-13)
# Text exploration (words, n-grams, sentiment)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.text 1.0.1 · spec 20003684d61078fb
# Dataset: s5_reviews (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_text_* (words, tokens, n-grams, tf-idf by group) and cs_text_vader (port of vaderSentiment 3.3.2)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s5_reviews.parquet", col_select = c("review text", "product")))
n_input <- nrow(df)
df[["review text"]] <- factor(df[["review text"]], levels = sort(unique(df[["review text"]]), method = "radix"))
df[["product"]] <- factor(df[["product"]], levels = c("coffee maker", "headphones", "running shoes"))  # stored level order
df <- df[stats::complete.cases(df[c("review text", "product")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("review text", "product"))  # infinite values stop the run (registry/errors.yaml)

# %% Texts
tc <- "review text"
gc <- "product"
groups <- as.character(df[[gc]])
g_levels <- intersect(c("coffee maker", "headphones", "running shoes"), groups)  # stored level order
texts <- as.character(df[[tc]])
n <- length(texts)
if (n == 0) stop(sprintf("%s has no texts.", tc))
n_gram <- as.integer("1")
top_n <- as.integer(20)
min_docs <- as.integer(2)
stop_words <- TRUE
lowercase <- TRUE
with_sentiment <- TRUE
ngram_label <- c("words", "two-word phrases", "three-word phrases")[n_gram]

# %% Profile
chars <- nchar(texts, type = "chars")
nwords <- vapply(texts, function(t) length(cs_text_words(t)), numeric(1), USE.NAMES = FALSE)
toks <- lapply(texts, cs_text_tokens, lowercase = lowercase)
grams <- lapply(toks, cs_text_ngrams, n = n_gram, stop = stop_words)
counts <- cs_text_count_terms(grams)
top <- cs_text_top_terms(counts, top_n, min_docs)
all_toks <- unlist(toks, use.names = FALSE)
n_tokens <- length(all_toks)
n_terms <- length(unique(all_toks))
classes <- c(letters = 0, digits = 0, whitespace = 0, punctuation = 0, other_ascii = 0, non_ascii = 0)
for (t in texts) {
  cc <- cs_text_char_classes(t)
  for (k in names(classes)) classes[[k]] <- classes[[k]] + cc[[k]]
}
total_chars <- sum(chars)
fl <- lapply(texts, cs_text_flags)
n_email <- sum(vapply(fl, function(f) f$email, logical(1)))
n_url <- sum(vapply(fl, function(f) f$url, logical(1)))
n_number <- sum(vapply(fl, function(f) f$number, logical(1)))
comp <- if (with_sentiment) vapply(texts, function(t) cs_text_vader(t)$compound, numeric(1), USE.NAMES = FALSE) else NULL

# %% Groups
group_rows <- list()
tfidf_rows <- list()
if (!is.null(gc)) {
  for (g in g_levels) {
    m <- groups == g
    row <- list(group = g, n = sum(m), words = mean(nwords[m]))
    if (!is.null(comp)) row <- c(row, list(sentiment = mean(comp[m]), positive = mean(comp[m] >= 0.05), negative = mean(comp[m] <= -0.05)))
    group_rows[[length(group_rows) + 1]] <- row
  }
  tfidf_rows <- cs_text_tfidf_by_group(stats::setNames(lapply(g_levels, function(g) grams[groups == g]), g_levels), top = min(top_n, 10), min_docs = 1)
}

# %% Assumptions
assumptions <- list(
  list(key = "language", label = "English text", status = "info",
       detail = "The stop list and VADER's lexicon are English; other languages need another tokenizer and sentiment model."),
  list(key = "privacy", label = "Personal data", status = if (n_email > 0) "warn" else "info",
       detail = sprintf("%d text(s) contain an e-mail address and %d a URL; consider marking %s sensitive in the data dictionary.", n_email, n_url, tc))
)
n_empty <- sum(nwords == 0)
if (n_empty > 0) warnings <- c(warnings, sprintf("%d text(s) are empty.", n_empty))

# %% Result
share <- function(k) if (total_chars > 0) classes[[k]] / total_chars else NA
values <- list(
  n_docs = n, n_empty = n_empty, chars_mean = mean(chars), chars_median = stats::median(chars), chars_max = max(chars),
  words_mean = mean(nwords), words_median = stats::median(nwords), words_max = max(nwords), words_total = sum(nwords),
  n_tokens = n_tokens, n_terms = n_terms, ttr = if (n_tokens > 0) n_terms / n_tokens else NA,
  share_letters = share("letters"), share_digits = share("digits"), share_whitespace = share("whitespace"),
  share_punctuation = share("punctuation"), share_non_ascii = share("non_ascii"),
  docs_email = n_email / n, docs_url = n_url / n, docs_number = n_number / n,
  top_terms_text = if (nrow(top) > 0) paste(sprintf("“%s”", utils::head(top$term, 5)), collapse = ", ") else "none (no term repeats often enough)",
  ngram_label = ngram_label, sentiment = with_sentiment, n_groups = length(g_levels),
  sentiment_mean = if (!is.null(comp)) mean(comp) else NA,
  sentiment_sd = if (!is.null(comp) && n > 1) stats::sd(comp) else NA,
  share_positive = if (!is.null(comp)) mean(comp >= 0.05) else NA,
  share_neutral = if (!is.null(comp)) mean(comp > -0.05 & comp < 0.05) else NA,
  share_negative = if (!is.null(comp)) mean(comp <= -0.05) else NA
)
for (i in seq_len(nrow(top))) values[[sprintf("term_count[%s]", top$term[i])]] <- top$count[i]
for (r in group_rows) {
  values[[sprintf("n[%s]", r$group)]] <- r$n
  if (!is.null(comp)) values[[sprintf("sentiment_mean[%s]", r$group)]] <- r$sentiment
}
class_labels <- c(letters = "Letters A–Z", digits = "Digits", whitespace = "Spaces and line breaks", punctuation = "ASCII punctuation",
                  other_ascii = "Other ASCII (control)", non_ascii = "Non-ASCII (accents, symbols, emoji, other scripts)")
tables <- list(
  list(key = "summary", title = "Texts", columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number")),
       rows = list(
         list(measure = "Texts", value = n), list(measure = "Empty texts", value = n_empty),
         list(measure = "Characters per text (mean)", value = values$chars_mean), list(measure = "Characters per text (median)", value = values$chars_median),
         list(measure = "Characters per text (max)", value = values$chars_max), list(measure = "Words per text (mean)", value = values$words_mean),
         list(measure = "Words per text (median)", value = values$words_median), list(measure = "Words per text (max)", value = values$words_max),
         list(measure = "Tokens (letter runs ≥ 2)", value = n_tokens), list(measure = "Distinct tokens", value = n_terms),
         list(measure = "Type–token ratio", value = values$ttr), list(measure = "Share of texts with an e-mail address", value = values$docs_email),
         list(measure = "Share of texts with a URL", value = values$docs_url), list(measure = "Share of texts with a digit", value = values$docs_number))),
  list(key = "terms", title = sprintf("Most frequent %s", ngram_label),
       columns = list(list(key = "rank", label = "#", type = "integer"), list(key = "term", label = "Term", type = "string"),
                      list(key = "count", label = "Occurrences", type = "integer"), list(key = "docs", label = "Texts", type = "integer"),
                      list(key = "share", label = "Share of texts", type = "number")),
       rows = lapply(seq_len(nrow(top)), function(i) list(rank = i, term = top$term[i], count = top$count[i], docs = top$docs[i], share = top$docs[i] / n)),
       note = paste0(if (stop_words) "Common English words left out. " else "", sprintf("Terms used in at least %d text(s).", min_docs))),
  list(key = "characters", title = "Characters",
       columns = list(list(key = "kind", label = "Kind", type = "string"), list(key = "count", label = "Count", type = "integer"), list(key = "share", label = "Share", type = "number")),
       rows = lapply(names(class_labels), function(k) list(kind = class_labels[[k]], count = classes[[k]], share = share(k))))
)
if (length(group_rows) > 0) {
  gcols <- list(list(key = "group", label = gc, type = "string"), list(key = "n", label = "Texts", type = "integer"), list(key = "words", label = "Mean words", type = "number"))
  if (!is.null(comp)) gcols <- c(gcols, list(list(key = "sentiment", label = "Mean sentiment", type = "number"), list(key = "positive", label = "Positive", type = "number"),
                                            list(key = "negative", label = "Negative", type = "number")))
  tables[[length(tables) + 1]] <- list(key = "groups", title = sprintf("By %s", gc), columns = gcols, rows = group_rows)
  tables[[length(tables) + 1]] <- list(key = "tfidf", title = sprintf("Terms that set each %s apart (tf-idf)", gc),
                                       columns = list(list(key = "group", label = gc, type = "string"), list(key = "rank", label = "#", type = "integer"),
                                                      list(key = "term", label = "Term", type = "string"), list(key = "count", label = "Occurrences", type = "integer"),
                                                      list(key = "tfidf", label = "tf-idf", type = "number")),
                                       rows = tfidf_rows, note = "Each group's texts are one document: tf = share of the group's terms, idf = ln(groups / groups using the term).")
}
charts <- list(cs_chart("terms", "ngram-bars", sprintf("Most frequent %s", ngram_label),
                        list(term = cs_col("Term", top$term, kind = "categorical"), count = cs_col("Occurrences", top$count)), controls = list(top = top_n)))
if (length(tfidf_rows) > 0 && length(g_levels) <= 9) {  # the chart draws at most 9 panels; the table has every group
  tv <- function(k) vapply(tfidf_rows, function(r) r[[k]], if (k == "tfidf") numeric(1) else character(1))
  charts[[length(charts) + 1]] <- cs_chart("tfidf", "ngram-bars", sprintf("Distinctive %s by %s", ngram_label, gc),
                                           list(term = cs_col("Term", tv("term"), kind = "categorical"), count = cs_col("tf-idf", tv("tfidf")),
                                                group = cs_col(gc, tv("group"), kind = "categorical", levels = g_levels)), controls = list(top = 10))
}
charts[[length(charts) + 1]] <- cs_chart("lengths", "histogram", "Words per text", list(x = cs_col("Words", nwords)))
if (!is.null(comp)) {
  charts[[length(charts) + 1]] <- if (!is.null(gc)) {
    cs_chart("sentiment", "raincloud", sprintf("Sentiment by %s", gc), list(y = cs_col("Sentiment (compound)", comp), group = cs_col(gc, groups, levels = g_levels)))
  } else {
    cs_chart("sentiment", "histogram", "Sentiment (VADER compound)", list(x = cs_col("Sentiment (compound)", comp)))
  }
}
summary <- sprintf("%d texts, %.1f words on average; top %s: %s%s", n, values$words_mean, ngram_label, values$top_terms_text,
                   if (!is.null(comp)) sprintf("; mean sentiment %.2f.", values$sentiment_mean) else ".")
cs_publish(list(
  method = "describe.text",
  methodVersion = "1.0.1",
  title = "Text exploration",
  engine = cs_engine_info("nanoparquet"),
  n = n,
  summary = summary,
  statistics = c(list(list(key = "n_docs", label = "Texts", value = n), list(key = "words_mean", label = "Mean words", value = values$words_mean),
                      list(key = "n_terms", label = "Distinct tokens", value = n_terms)),
                 if (!is.null(comp)) list(list(key = "sentiment_mean", label = "Mean sentiment", value = values$sentiment_mean)) else list()),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = if (!is.null(comp)) list("Sentiment: VADER compound score (−1 to 1); positive ≥ 0.05, negative ≤ −0.05, neutral in between (Hutto & Gilbert 2014).") else list(),
  charts = charts,
  values = values
))
Python

59 texts, 8.2 words on average; top words: “good”, “great”, “coffee”, “comfortable”, “nothing”; mean sentiment 0.19.

Texts
59
Mean words
8.153
Distinct tokens
282
Mean sentiment
0.1880

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • English text — The stop list and VADER's lexicon are English; other languages need another tokenizer and sentiment model.
  • Personal data — 1 text(s) contain an e-mail address and 1 a URL; consider marking review text sensitive in the data dictionary.

Texts

MeasureValue
Texts59
Empty texts1
Characters per text (mean)47.542
Characters per text (median)48
Characters per text (max)77
Words per text (mean)8.153
Words per text (median)8
Words per text (max)12
Tokens (letter runs ≥ 2)462
Distinct tokens282
Type–token ratio0.6104
Share of texts with an e-mail address0.0169
Share of texts with a URL0.0169
Share of texts with a digit0.0847

Most frequent words

#TermOccurrencesTextsShare of texts
1good550.0847
2great550.0847
3coffee440.0678
4comfortable440.0678
5nothing430.0508
6best330.0508
7headphones330.0508
8love330.0508
9re330.0508
10absolutely220.0339
11brew220.0339
12carafe220.0339
13com220.0339
14cup220.0339
15cushioning220.0339
16example220.0339
17fantastic220.0339
18fine220.0339
19happy220.0339
20left220.0339

Common English words left out. Terms used in at least 2 text(s).

Characters

KindCountShare
Letters A–Z2,2410.7989
Digits140.0050
Spaces and line breaks4230.1508
ASCII punctuation1200.0428
Other ASCII (control)00
Non-ASCII (accents, symbols, emoji, other scripts)70.0025

By product

productTextsMean wordsMean sentimentPositiveNegative
coffee maker207.9000.12660.45000.3500
headphones208.6500.18470.55000.3500
running shoes197.8950.25610.63160.2632

Terms that set each product apart (tf-idf)

product#TermOccurrencestf-idf
coffee maker1coffee40.0458
coffee maker2brew20.0229
coffee maker3carafe20.0229
coffee maker4morning20.0229
coffee maker5annoying10.0114
coffee maker6build10.0114
coffee maker7burnt10.0114
coffee maker8cheap10.0114
coffee maker9clean10.0114
coffee maker10constantly10.0114
headphones1headphones30.0297
headphones2com20.0198
headphones3example20.0198
headphones4much20.0198
headphones5noise20.0198
headphones6review20.0198
headphones7sound20.0198
headphones8worst20.0198
headphones9amazing10.0099
headphones10anc10.0099
running shoes1cushioning20.0234
running shoes2look20.0234
running shoes3perfect20.0234
running shoes4runs20.0234
running shoes5shoes20.0234
running shoes6size20.0234
running shoes7average10.0117
running shoes8beginners10.0117
running shoes9blisters10.0117
running shoes10break10.0117

Each group's texts are one document: tf = share of the group's terms, idf = ln(groups / groups using the term).

  • 1 of 60 rows were left out because a value was missing.
  • 1 text(s) are empty.
  • Sentiment: VADER compound score (−1 to 1); positive ≥ 0.05, negative ≤ −0.05, neutral in between (Hutto & Gilbert 2014).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Text exploration (words, n-grams, sentiment)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.text 1.0.1 · spec 20003684d61078fb
# Dataset: s5_reviews (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.text import explore as tx  # words, tokens, n-grams, tf-idf by group (twins of codesplashr cs_text_*)
from codesplash.text import vader  # VADER sentiment: port of vaderSentiment 3.3.2 (twin: cs_text_vader)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s5_reviews.parquet", columns=["review text", "product"])
n_input = len(df)
df["review text"] = pd.Categorical(df["review text"], categories=sorted(df["review text"].dropna().unique()))
df["product"] = pd.Categorical(df["product"], categories=["coffee maker", "headphones", "running shoes"])  # stored level order
df = df.dropna(subset=["review text", "product"])  # listwise deletion over the analysis columns
df["review text"] = df["review text"].cat.remove_unused_categories()
df["product"] = df["product"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["review text", "product"])  # infinite values stop the run (registry/errors.yaml)

# %% Texts
tc = "review text"
gc = "product"
g_levels = [lv for lv in ["coffee maker", "headphones", "running shoes"] if lv in set(df[gc].astype(str))]  # stored level order
groups = df[gc].astype(str).tolist()
texts = df[tc].astype(str).tolist()
n = len(texts)
if n == 0:
    raise ValueError(f"{tc} has no texts.")
n_gram = int("1")
top_n, min_docs = int(20), int(2)
stop, lowercase, with_sentiment = True, True, True
ngram_label = {1: "words", 2: "two-word phrases", 3: "three-word phrases"}[n_gram]

# %% Profile
chars = np.array([len(t) for t in texts], dtype=float)
nwords = np.array([len(tx.words(t)) for t in texts], dtype=float)
toks = [tx.tokens(t, lowercase) for t in texts]
grams = [tx.ngrams(tk, n_gram, stop) for tk in toks]
counts = tx.count_terms(grams)
top = tx.top_terms(counts, top_n, min_docs)
all_toks = [w for tk in toks for w in tk]
n_tokens, n_terms = len(all_toks), len(set(all_toks))
classes = {k: 0 for k in ("letters", "digits", "whitespace", "punctuation", "other_ascii", "non_ascii")}
for t in texts:
    for k, v in tx.char_classes(t).items():
        classes[k] += v
total_chars = int(chars.sum())
fl = [tx.flags(t) for t in texts]
comp = np.array([vader.scores(t)["compound"] for t in texts]) if with_sentiment else None

# %% Groups
group_rows, tfidf_rows = [], []
if gc is not None:
    garr = np.array(groups)
    for g in g_levels:
        m = garr == g
        row = {"group": g, "n": int(m.sum()), "words": float(nwords[m].mean())}
        if comp is not None:
            row.update({"sentiment": float(comp[m].mean()), "positive": float(np.mean(comp[m] >= 0.05)), "negative": float(np.mean(comp[m] <= -0.05))})
        group_rows.append(row)
    tfidf_rows = tx.tfidf_by_group({g: [grams[i] for i in range(n) if groups[i] == g] for g in g_levels}, top=min(top_n, 10), min_docs=1)

# %% Assumptions
assumptions = [
    {"key": "language", "label": "English text", "status": "info",
     "detail": "The stop list and VADER's lexicon are English; other languages need another tokenizer and sentiment model."},
    {"key": "privacy", "label": "Personal data", "status": "warn" if any(f["email"] for f in fl) else "info",
     "detail": f"{sum(f['email'] for f in fl)} text(s) contain an e-mail address and {sum(f['url'] for f in fl)} a URL; consider marking {tc} sensitive in the data dictionary."},
]
n_empty = int(np.sum(nwords == 0))
if n_empty:
    warnings.append(f"{n_empty} text(s) are empty.")

# %% Result
share = (lambda k: classes[k] / total_chars) if total_chars else (lambda k: None)
values = {
    "n_docs": n, "n_empty": n_empty, "chars_mean": float(chars.mean()), "chars_median": float(np.median(chars)), "chars_max": float(chars.max()),
    "words_mean": float(nwords.mean()), "words_median": float(np.median(nwords)), "words_max": float(nwords.max()), "words_total": float(nwords.sum()),
    "n_tokens": n_tokens, "n_terms": n_terms, "ttr": n_terms / n_tokens if n_tokens else None,
    "share_letters": share("letters"), "share_digits": share("digits"), "share_whitespace": share("whitespace"),
    "share_punctuation": share("punctuation"), "share_non_ascii": share("non_ascii"),
    "docs_email": sum(f["email"] for f in fl) / n, "docs_url": sum(f["url"] for f in fl) / n, "docs_number": sum(f["number"] for f in fl) / n,
    "top_terms_text": ", ".join(f"“{t}”" for t, _, _ in top[:5]) if top else "none (no term repeats often enough)",
    "ngram_label": ngram_label, "sentiment": with_sentiment, "n_groups": len(g_levels),
    "sentiment_mean": float(comp.mean()) if comp is not None else None,
    "sentiment_sd": float(comp.std(ddof=1)) if comp is not None and n > 1 else None,
    "share_positive": float(np.mean(comp >= 0.05)) if comp is not None else None,
    "share_neutral": float(np.mean((comp > -0.05) & (comp < 0.05))) if comp is not None else None,
    "share_negative": float(np.mean(comp <= -0.05)) if comp is not None else None,
}
for i, (t, c, d) in enumerate(top, start=1):
    values[f"term_count[{t}]"] = c
for r in group_rows:
    values[f"n[{r['group']}]"] = r["n"]
    if comp is not None:
        values[f"sentiment_mean[{r['group']}]"] = r["sentiment"]
tables = [
    {"key": "summary", "title": "Texts", "columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
     "rows": [
        {"measure": "Texts", "value": n}, {"measure": "Empty texts", "value": n_empty},
        {"measure": "Characters per text (mean)", "value": values["chars_mean"]}, {"measure": "Characters per text (median)", "value": values["chars_median"]},
        {"measure": "Characters per text (max)", "value": values["chars_max"]}, {"measure": "Words per text (mean)", "value": values["words_mean"]},
        {"measure": "Words per text (median)", "value": values["words_median"]}, {"measure": "Words per text (max)", "value": values["words_max"]},
        {"measure": "Tokens (letter runs ≥ 2)", "value": n_tokens}, {"measure": "Distinct tokens", "value": n_terms},
        {"measure": "Type–token ratio", "value": values["ttr"]}, {"measure": "Share of texts with an e-mail address", "value": values["docs_email"]},
        {"measure": "Share of texts with a URL", "value": values["docs_url"]}, {"measure": "Share of texts with a digit", "value": values["docs_number"]}]},
    {"key": "terms", "title": f"Most frequent {ngram_label}", "columns": [
        {"key": "rank", "label": "#", "type": "integer"}, {"key": "term", "label": "Term", "type": "string"},
        {"key": "count", "label": "Occurrences", "type": "integer"}, {"key": "docs", "label": "Texts", "type": "integer"},
        {"key": "share", "label": "Share of texts", "type": "number"}],
     "rows": [{"rank": i, "term": t, "count": c, "docs": d, "share": d / n} for i, (t, c, d) in enumerate(top, start=1)],
     "note": ("Common English words left out. " if stop else "") + f"Terms used in at least {min_docs} text(s)."},
    {"key": "characters", "title": "Characters", "columns": [
        {"key": "kind", "label": "Kind", "type": "string"}, {"key": "count", "label": "Count", "type": "integer"}, {"key": "share", "label": "Share", "type": "number"}],
     "rows": [{"kind": lab, "count": classes[k], "share": share(k)} for k, lab in (
        ("letters", "Letters A–Z"), ("digits", "Digits"), ("whitespace", "Spaces and line breaks"), ("punctuation", "ASCII punctuation"),
        ("other_ascii", "Other ASCII (control)"), ("non_ascii", "Non-ASCII (accents, symbols, emoji, other scripts)"))]},
]
if group_rows:
    gcols = [{"key": "group", "label": gc, "type": "string"}, {"key": "n", "label": "Texts", "type": "integer"}, {"key": "words", "label": "Mean words", "type": "number"}]
    if comp is not None:
        gcols += [{"key": "sentiment", "label": "Mean sentiment", "type": "number"}, {"key": "positive", "label": "Positive", "type": "number"},
                  {"key": "negative", "label": "Negative", "type": "number"}]
    tables.append({"key": "groups", "title": f"By {gc}", "columns": gcols, "rows": group_rows})
    tables.append({"key": "tfidf", "title": f"Terms that set each {gc} apart (tf-idf)", "columns": [
        {"key": "group", "label": gc, "type": "string"}, {"key": "rank", "label": "#", "type": "integer"}, {"key": "term", "label": "Term", "type": "string"},
        {"key": "count", "label": "Occurrences", "type": "integer"}, {"key": "tfidf", "label": "tf-idf", "type": "number"}],
        "rows": tfidf_rows, "note": "Each group's texts are one document: tf = share of the group's terms, idf = ln(groups / groups using the term)."})
charts = [cs.chart("terms", "ngram-bars", f"Most frequent {ngram_label}", {
    "term": cs.col("Term", [t for t, _, _ in top], kind="categorical"), "count": cs.col("Occurrences", [c for _, c, _ in top])}, controls={"top": top_n})]
if tfidf_rows and len(g_levels) <= 9:  # the chart draws at most 9 panels; the table has every group
    charts.append(cs.chart("tfidf", "ngram-bars", f"Distinctive {ngram_label} by {gc}", {
        "term": cs.col("Term", [r["term"] for r in tfidf_rows], kind="categorical"), "count": cs.col("tf-idf", [r["tfidf"] for r in tfidf_rows]),
        "group": cs.col(gc, [r["group"] for r in tfidf_rows], kind="categorical", levels=g_levels)}, controls={"top": 10}))
charts.append(cs.chart("lengths", "histogram", "Words per text", {"x": cs.col("Words", nwords)}))
if comp is not None:
    if gc is not None:
        charts.append(cs.chart("sentiment", "raincloud", f"Sentiment by {gc}", {"y": cs.col("Sentiment (compound)", comp), "group": cs.col(gc, groups, levels=g_levels)}))
    else:
        charts.append(cs.chart("sentiment", "histogram", "Sentiment (VADER compound)", {"x": cs.col("Sentiment (compound)", comp)}))
summary = (f"{n} texts, {values['words_mean']:.1f} words on average; top {ngram_label}: {values['top_terms_text']}"
           + (f"; mean sentiment {values['sentiment_mean']:.2f}." if comp is not None else "."))
cs.publish({
    "method": "describe.text",
    "methodVersion": "1.0.1",
    "title": "Text exploration",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": n,
    "summary": summary,
    "statistics": [{"key": "n_docs", "label": "Texts", "value": n}, {"key": "words_mean", "label": "Mean words", "value": values["words_mean"]},
                   {"key": "n_terms", "label": "Distinct tokens", "value": n_terms}]
    + ([{"key": "sentiment_mean", "label": "Mean sentiment", "value": values["sentiment_mean"]}] if comp is not None else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Sentiment: VADER compound score (−1 to 1); positive ≥ 0.05, negative ≤ −0.05, neutral in between (Hutto & Gilbert 2014)."] if comp is not None else [],
    "charts": charts,
    "values": values,
})

Then try the options on your own text: single words, two-word phrases or three-word phrases, and a group column to compare.

04

Sentiment, with care

Reflect

The mean sentiment score here is 0.19, with 54.2% of reviews positive and 32.2% negative.

This is lexicon sentimentLexicon sentimentScores a text's tone by looking its words up in a list of scored words, with a few rules for things like simple negation., using VADER's word list and a few rules for things like simple negation. It can't read sarcasm or domain meanings, such as "sick" in a skate review.

How would you check it on your own data? Read a sample of texts it scored high and low.

05

Vocabulary richness

Read

The type–token ratio divides distinct words by total words. It's 0.61 here. Low values mean repetition, such as templated text. But it falls as texts get longer, so compare only between sets of similar length.

The Top terms chart shows the frequency table:

Top termsWhich words or phrases appear most in a text column, overall or by group?
View data
bigramcountrating
late delivery621–2 stars
refund501–2 stars
customer service451–2 stars
broken391–2 stars
never arrived331–2 stars
waste251–2 stars
wrong size251–2 stars
poor quality241–2 stars
support181–2 stars
return181–2 stars
great quality744–5 stars
fast shipping604–5 stars
love524–5 stars
fits perfectly384–5 stars
easy354–5 stars
recommend334–5 stars
comfortable314–5 stars
good value264–5 stars
gift164–5 stars
soft174–5 stars
06

Going further

Read

For topics, use Discover. For features in a model, use Text features or Text to term columns in Prepare.

07

Check your understanding

Checkpoint

Check yourself

A lexicon score rates "Great, another phone that dies by lunch" as positive. Why?

Show the answer

Answer: a

Word lists and simple rules don't understand what a sentence means. Treat the score as a rough description, and read examples.

Check yourself

A text set has 400 distinct words and 800 words in total. What's its type–token ratio?

Show the answer

Answer: 0.5

400 / 800.

Check yourself

The two-word phrase "customer service" tops your list, and neither word is in the top ten. Why does the phrase view help?

Show the answer

Answer: a

An n-gram counts adjacent words together, so a phrase can surface when its parts look ordinary.

08

Recap

Recap
  • Profile text first: length, empties, duplicates and personal data.
  • Remove common words to see what the texts are about.
  • Lexicon sentiment is a rough description, so read samples before you trust it.

Concepts in this lesson