1. Text analysis pipeline
When you hear “text analysis,” it’s easy to imagine something scary: neural networks, linguistics, and an instructor who says “it’s obvious.” In reality, in a simple learning Text Analyzer almost everything rests on a very down-to-earth idea: we consistently transform one data type into another until we get a convenient result. That’s the pipeline: several steps, each with a clear input and output.
Imagine you’re given a large text and asked: “Which words occur most often?” If you implement it “head-on,” you can drown in loops, temporary variables, and checks. A pipeline saves you because you do exactly 5–6 standard steps: normalization → tokens → frequencies → sorting → top-N → formatting. And at each step you end up with a structure that’s pleasant to work with.
Here’s the diagram (very technical, but honest):
flowchart TD
A["Raw text (String)"] --> B["Normalized text (String)"]
B --> C["Tokens (List⟨String⟩)"]
C --> D["Frequencies (Map⟨String, Int⟩)"]
D --> E["Sorted items (List⟨Entry⟩)"]
E --> F["Top-N (List⟨Pair⟨String, Int⟩⟩)"]
F --> G["Report (String)"]
The main trick: we’re not “trying to solve everything at once”; each time we make a small transition between understandable types.
Type map across pipeline steps
So the pipeline doesn’t turn into magic, it helps to keep a “type map” in your head in advance: what you had and what you got. Then the code reads like a route in a navigator rather than a quest of “find where the bracket disappeared.”
Below is a practical table you can come back to when you catch yourself thinking, “Why is it entries here and not map?”
| Step | What we do | Input | Output | Example operations |
|---|---|---|---|---|
|
Normalize the text | |
|
|
|
Tokenize | |
|
|
|
Count frequencies | |
|
|
|
Select top-N | |
List<Map.Entry<String, Int>> or List<Pair<String, Int>> | |
|
Format | list of Pair/Entry | |
|
Important: for now we’re building a simple analyzer. We’re not doing “smart tokenization,” not accounting for every punctuation mark in the world, and not deciding the fate of the hyphen in the word “mother-of-a-programmer.” We’re building a reliable base pipeline that can be improved later.
2. Text normalization
Text normalization is the moment when you convert user input into a form suitable for honest processing. A user can paste text with line breaks, multiple spaces, tabs, and random uppercase letters. If we start split() directly on this “raw” input, we’ll get garbage: empty tokens, “Kotlin” separate from “kotlin,” and weird frequency results.
Mini-normalization: trim() and lowercase()
Let’s start with the most basic. We’ll remove spaces at the edges and convert everything to lowercase. This already sharply reduces “noise.”
fun main() {
val raw = " Kotlin KOTLIN kotlin "
val normalized = raw.trim().lowercase()
println(normalized) // kotlin kotlin kotlin
}
The idea here is simple: if case doesn’t matter for meaning (and in our analyzer it doesn’t), it’s better to normalize the case right away.
Normalizing whitespace with Regex("""\s+""").replace(...)
Now a beginner’s pain: “Why do I have empty strings after split(" ")?” Usually because the text contains many spaces, line breaks, and tabs. We want to “collapse” any sequence of whitespace characters into one regular space.
import kotlin.text.Regex
fun main() {
val raw = " Kotlin Kotlin \n is\tgreat "
val spaces = Regex("""\s+""")
val normalized = spaces.replace(raw.trim().lowercase(), " ")
println(normalized) // kotlin kotlin is great
}
Pay attention to "\s+". It means “one or more whitespace characters.” That is, both spaces and "\n" and "\t" are converted to the same form. After that, tokenization becomes predictable.
If after normalization the text turns out to be empty, it’s convenient to immediately choose a fallback scenario via takeIf { ... } ?: ... . This is that style of “take the value if it fits, otherwise default,” which reads linearly.
3. Tokenization
Tokenization sounds like a scary word, but in our context it literally means “split a string into words.” The important thing is not to rush: if you do split(" ") on dirty text, you’ll get empty elements. If you’ve already normalized whitespace, the task becomes almost boring—and that’s a great sign of correct code.
Simple tokenization after normalization
Assume we already have a string where there is exactly one space between words. Then split(" ") will work consistently.
fun main() {
val normalized = "kotlin kotlin is great"
val tokens = normalized.split(" ")
println(tokens) // [kotlin, kotlin, is, great]
}
Filtering empty tokens: filter { it.isNotBlank() }
Even if you try hard, “dirt” can still slip through. For example, the user entered only spaces, or normalization doesn’t handle some edge case yet. So filtering with isNotBlank() is a cheap and useful safety net.
fun main() {
val normalized = "kotlin kotlin " // intentionally "dirty"
val tokens = normalized
.split(" ")
.filter { it.isNotBlank() }
println(tokens) // [kotlin, kotlin]
}
This filter doesn’t do magic—it simply throws away empty strings and strings made of spaces. And it’s exactly that “small step” that makes the whole pipeline more robust.
4. Counting frequencies
This is where the nicest part begins: we’re no longer messing with a string, we’re working with a proper collection List<String>. And our goal is to get a Map<String, Int>, where the key is the word and the value is how many times it occurred.
In the good old days (roughly yesterday) you might have used a MutableMap and manually incremented a counter. That’s a useful skill, but Kotlin offers a more compact and readable option: groupingBy { ... }.eachCount().
fun main() {
val tokens = listOf("kotlin", "kotlin", "is", "great", "great")
val freq: Map<String, Int> = tokens.groupingBy { it }.eachCount()
println(freq) // {kotlin=2, is=1, great=2}
}
Why is this convenient specifically as a pipeline step? Because on output we get a structure that perfectly matches the “top-N” task: frequencies are already counted; all that’s left is to pick the biggest ones.
5. Selecting top-N
A naive idea sounds like this: “I want to sort a Map.” And here Kotlin will gently hint that a Map is not a list, and you can’t sort a “map” directly the same way you sort a list. But a Map has entries: a set of key–value pairs that you can turn into a list and sort however you like.
Top-N via entries → sortedByDescending → take
fun main() {
val freq = mapOf("kotlin" to 2, "is" to 1, "great" to 2, "fun" to 5)
val top2 = freq.entries
.sortedByDescending { it.value }
.take(2)
for (e in top2) {
println("${e.key}: ${e.value}")
// fun: 5
// kotlin: 2 (or great: 2 — we don't fix the order on ties)
}
}
There’s an important nuance for beginners: if values are equal (for example, kotlin=2 and great=2), the exact order between them is usually not important. Later you can add a secondary alphabetical sort, but in this lecture we keep the focus on the base pipeline.
Converting Entry to Pair
Sometimes an Entry is inconvenient for formatting. Then you can take one more small step: convert Entry into a Pair<String, Int>.
fun main() {
val freq = mapOf("kotlin" to 2, "is" to 1, "great" to 2)
val top = freq.entries
.sortedByDescending { it.value }
.take(2)
.map { it.key to it.value }
println(top) // [(kotlin, 2), (great, 2)] (or the other way around on ties)
}
Notice how this fits into the pipeline philosophy: one more simple data transformation to make the next step easier.
6. Report formatting
Up to this point we were “honestly counting,” and that was the computational part. Now comes presenting the result to the user: we want a nice report string that we can print with println. Here it’s important not to start mixing counting logic with formatting logic. Even if you do everything in one main, keep in mind: “here I count, and here I show.”
Printing with joinToString("\n")
fun main() {
val top = listOf("fun" to 5, "kotlin" to 2, "is" to 1)
val report = top.joinToString(separator = "\n") { (word, count) ->
"$word: $count"
}
println(report)
// fun: 5
// kotlin: 2
// is: 1
}
Destructuring (word, count) works here because Pair supports component functions. The result is compact and readable.
A bit of alignment with padEnd and padStart
We already covered padStart/padEnd on strings, so we can make the report a bit cleaner so the numbers line up in a column.
fun main() {
val top = listOf("fun" to 5, "kotlin" to 12, "is" to 1)
val report = top.joinToString(separator = "\n") { (word, count) ->
"${word.padEnd(10)} | ${count.toString().padStart(3)}"
}
println(report)
// fun | 5
// kotlin | 12
// is | 1
}
This is still not a “big formatter,” just a pleasant look for the console.
7. Building a mini Text Analyzer app
Now we’ll do what the pipeline was for in the first place: connect the steps into one scenario. The idea is: read text, normalize, tokenize, count frequencies, take top-N, and print the report. We’re not extracting steps into separate functions yet—that will be the next lecture. For now, it’s more important to feel the linearity of transformations and see how types “move” from step to step.
Variant with intermediate val
import kotlin.text.Regex
fun main() {
println("Enter text:")
val rawText = readln()
val normalized = Regex("""\s+""").replace(rawText.trim().lowercase(), " ")
val tokens = normalized.split(" ").filter { it.isNotBlank() }
val freq = tokens.groupingBy { it }.eachCount()
val topN = freq.entries
.sortedByDescending { it.value }
.take(5)
.map { it.key to it.value }
val report = topN.joinToString("\n") { (w, c) -> "$w: $c" }
println(report)
}
This code is “a bit longer,” but it honestly shows the thought: a string became a list, the list became a map, the map became top-N, and top-N became text. For first attempts, this is better than a “super chain in 1 line.”
Chained variant with scope functions
If you already know scope functions from the previous lecture, you can assemble the result in a more “pipeline-ish” way. Here also is convenient for inserting debug output without breaking the main result (it returns the original object).
import kotlin.text.Regex
fun main() {
val report = readln()
.let { Regex("""\s+""").replace(it.trim().lowercase(), " ") }
.also { println("Normalized: $it") } // Normalized: ...
.split(" ")
.filter { it.isNotBlank() }
.groupingBy { it }.eachCount()
.entries
.sortedByDescending { it.value }
.take(5)
.joinToString("\n") { "${it.key}: ${it.value}" }
println(report)
}
It’s important not to try to write this way all the time. This style is good when the chain is short and readable. If you start getting confused about where you have a String, where you have a List, and where you have a Map, it’s better to go back to intermediate vals—this is not a “loss,” it’s normal engineering caution.
8. Common mistakes when assembling a Text Analyzer pipeline
Mistake #1: tokenization before normalization.
If you start with split(" ") on raw text, you’ll almost certainly get empty tokens and strange results. The problem isn’t split, but the fact that spaces can be repeated, plus there are "\n" and "\t". First normalize whitespace to a single space, and only then split into words.
Mistake #2: forgot isNotBlank() filtering and got surprised by empty “words.”
Even after normalization, edge cases can remain: empty input, leading/trailing spaces, unexpected combinations. If you don’t discard empty tokens, you can end up with the “word” "", and it will suddenly become the most frequent one (because emptiness is very popular... philosophers would approve, but users wouldn’t).
Mistake #3: trying to “sort a Map directly.”
A Map is a “key → value” structure, while sorting is a story about ordered collections. So the correct path is almost always: freq.entries → sortedByDescending { it.value } → take(n). Once you accept this as normal, top-N stops being a mystery.
Mistake #4: mixing counting and formatting into one mess.
When you count frequencies and at the same time build a multi-line string right in the process, the code quickly becomes unreadable: it’s unclear where the logic ends and where the “pretty output” begins. Even if you write everything in one main, keep the formatting stage as a separate final step (for example, as a separate variable report).
Mistake #5: an overly clever chain where you lost the types.
Scope functions and operation chains are great, but they shouldn’t turn into a magic trick with a disappearing rabbit. If in the middle of the chain you’re no longer sure what you have in your hands (String? List<String>? Map<String, Int>?), stop, introduce intermediate vals, and give them good names. This doesn’t slow a programmer down—it speeds up debugging.
GO TO FULL VERSION