1. Text analysis paipeline
“Text analysis”reul deureumyeon swipge eotteon museoun geoseul sangsanghage doemnida: neural network, linguistics, geurigo gangsa-ga “igeo obvious haejyo”rago malhaneun geot. Hajiman silje-ro, gandanhan gyoyuk-yong Text Analyzer-neun geoui modu aju “hyeonsiljeog”in aidi-e uihae jiwontoeo it습니다. Uri-neun han gae-ui data typeeul dareun typeuro yeonsokjeog-euro bakkumyeonseo, gyeolguk cheori-hagi pyeonhan gyeolgwa-reul eokseumnida. Igeot-i baro paipeline-imnida: yeoreo dan-gye, geurigak dan-gye-neun myeonghwakhan input-gwa output-i itseumnida.
Keun texteul han beon badeun dwi “Eotteon dan-eoga gajang jarju deungjanghajyo?”rago muleobonda-go sangsanghae bopsida. Igeol “jeongmyeon dolpa”sik-euro (jeongjikage) sseumyeon, loop, imsi byeonsu, chekeu deul-e ppajyeo heundeulligi swip습니다. Paipeline-ui jom-eun, jeongmalro piryohan 5–6gae-ui pyojun dan-gye-man balpan samaneun geot입니다: jeonggyuhwa → token → bindo → jeongryeol → top‑N → formatting. Geurigak dan-gye마다, jageop-hagi joh-eun gujo-ga naomyeonseo kodeu-ga pyeonanhaejimnida.
Da-eum-eun seukima-imnida (aju technical hajiman, 솔직합니다):
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)"]
Haeksim: “han beon-e modu-reul haegyeolharyeogo” haji 않고, 매번 “ihal ganeunhan type” sai-eui jageun ihaeng-eul han dan-gye-ssik haebomnida.
Paipeline dan-gye byeol type map
Paipeline-eul “magic”cheoreom boiji anke 하려면, 미리 “type map”eul meoritsok-e deulgo itneun geosi yuyong합니다: eotteon geot-i eotteon geot-euro bakkwiejyeotneunji. Geureom kodeu-ga navigator-ui gyeongro-cheoreom 읽히고, “eodiseo 괄호가 sarajyeotji chajgi” 같은 quest-ro byeonhaji 않습니다.
A래eun, “wae yeogi-eun entriesigo mapi aniji?”rago dasi saenggakhage doel ttae doraol su itneun siljeon table-imnida.
| Step | What we do | Input | Output | Example operations |
|---|---|---|---|---|
|
Normalize text | |
|
|
|
Tokenize | |
|
|
|
Count frequencies | |
|
|
|
Select top‑N | |
List<Map.Entry<String, Int>> or List<Pair<String, Int>> | |
|
Format | list of Pair/Entry | |
|
Jung-yo: ajik uri-neun simple analyzer-reul mandeuneun jung입니다. “Smart tokenization”e deureogaji 않go, sesang-ui modu punctuation-eul da cheori하지 않으며, “mother‑of‑a‑programmer” 같은 hyphen-i dan-eo-e seo eotteohge cheori-doelji gyeoljeonghaji도 않습니다. Uri-neun 나중에 gaeseonhal su itneun, mid-eum-jikhan gibon paipeline-eul seuntet-eke 쌓는 geot-i moksu-imnida.
2. Text normalization
Text normalization-eun, user input-eul “jeongjikhan processing”e jeokhap-han hyeongtae-ro bakkuneun dan-gye-imnida. User-neun line break, yeoreo gae-ui space, tab, geurigo uibunbyeolhan capital letter-leul seok-eo neul su it습니다. I “raw”han geot-eul geudaero split()hae beorimyeon, garbage-ga naomyeonseo: 빈 token, “Kotlin”eul “kotlin”gwa ddaro segigo, bindo-gyeol-gwa-do isanghaejimnida.
Mini normalization: trim() and lowercase()
Gajang gibonbuteo sijakhapnida. Yang kkeut-ui 공백-eul jegeo하고, modu lowercase-ro bakkumnida. I geot만으로도 “noise”ga keuge 줄어듭니다.
fun main() {
val raw = " Kotlin KOTLIN kotlin "
val normalized = raw.trim().lowercase()
println(normalized) // kotlin kotlin kotlin
}
Yeogi-ui aidi-eun dan순합니다: case-ga uimi-e yeonghyang-eul an jundamyeon (uri analyzer-eseo-neun an jumnida), cheoeum-buteo han 가지 case-ro 통일하는 게 좋습니다.
Normalize spaces with Regex("""\s+""").replace(...)
Chobo-ui “piseo” 포인트: “wae split(" ") haessdeoni 빈 문자열-i 나오죠?” 대개 texte-e space, line break, tab-i manhgi 때문입니다. Uri-neun eotteon “whitespace sequence”라도 han gae-ui ilban spacelo “collapse”하고 싶습니다.
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
}
"\s+"e jom jujihaseyo. Igeon “하나 이상의 whitespace”입니다. 즉 space-do, "\n"do, "\t"do modu han 가지 형태로 맞춥니다. Ihu tokenization-i 예측 가능해집니다.
Jeonggyuhwa 후 text-ga bi-eosseumyeon, takeIf { ... } ?: ... 로 바로 backup scenario-reul seontaekhagi pyeon합니다. Igeon “jogeon-eul manjokhals ttae-man 값 사용, 아니면 default”라는 style-lo, linearl하게 읽힙니다.
3. Tokenization
Tokenization-eun museoun malcheoreom 들리지만, uri context-eseo-neun geunyang “munjayeol-eul dan-eoro nareuneun geot”입니다. Yeogi-seo seodureuji mareyo: dirty text-e daehae split(" ")hae beorimyeon 빈 element-ga saenggimnida. 반대로 whitespace normalization-eul haessdamyeon, munje-neun geoui boringhaejimnida — geu geot-i baro jal jjeojin kodeu-ui jopyeon입니다.
Simple tokenization after normalization
이미 단어 사이가 딱 하나의 space로 정리된 문자열이 있다고 가정합시다. Geureom split(" ")eun 안정적으로 동작합니다.
fun main() {
val normalized = "kotlin kotlin is great"
val tokens = normalized.split(" ")
println(tokens) // [kotlin, kotlin, is, great]
}
Filtering empty tokens: filter { it.isNotBlank() }
아무리 신경 써도 “dirt”가 가끔 스며듭니다. 예를 들면 user-ga 공백만 입력했거나, normalization이 아직 어떤 case를 반영하지 못했을 수도 있습니다. 그래서 isNotBlank() filtering-eun 싸고 유용한 보험입니다.
fun main() {
val normalized = "kotlin kotlin " // intentionally "dirty"
val tokens = normalized
.split(" ")
.filter { it.isNotBlank() }
println(tokens) // [kotlin, kotlin]
}
Yeogi filter-neun magic-eul 부리지 않습니다 — 단지 빈 문자열과 공백만 있는 문자열을 버립니다. Geurigo i geot-i baro paipeline-eul 더 튼튼하게 만드는 “jageun han georeum”입니다.
4. Counting frequencies
Yeogi-seo buteo gajang joh-eun part-ga sijakdoemnida: 더 이상 munjayeol-eul jjinppalgae 다루지 않고, List<String> 같은 정상적인 collection-eul 다룹니다. Uri-ui moksu-eun Map<String, Int>를 얻는 것입니다. key-neun dan-eo, value-neun deungjang 횟수입니다.
Yesjeon yesjeon (eonje? daeumjeon, eojje) style-eseo-neun MutableMape 카운터를 수동으로 올렸을 수도 있습니다. Igeon yuyonghan skill-ijiman, Kotlin-eun 더 compact하고 읽기 쉬운 bangbeob-eul 제공합니다: 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}
}
Wae i geot-i paipeline step-euroseon joteulkka-yo? Output-ui gujo-ga “top‑N” munje-e jeongmalro 딱 맞기 때문입니다: bindo-neun 이미 계산되었고, 이제 큰 것들만 골라내면 됩니다.
5. Selecting top‑N
Chobo-jeok aidi-eun daechae ireon geos입니다: “Mapeul sort 하고 싶어요.” Geureom Kotlin-i bu드럽게 알려줍니다: Mapeun list-ga 아니고, list처럼 “directly sort”할 수 없습니다. Hajiman Mapeun entriesreul 제공합니다: “key‑value” pair set이며, 이를 list로 바꿔서 원하는 대로 정렬할 수 있습니다.
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 — tie order is not fixed)
}
}
Chobo-ege jung-yohan nuance-ga itseumnida: 값이 같으면 (예: kotlin=2와 great=2), 그 둘 사이의 정확한 순서는 보통 중요하지 않습니다. 나중에 알파벳 순의 2차 정렬을 추가할 수 있지만, i lecture-eseo-neun gibon paipeline-e 집중합니다.
Converting Entry to Pair
Gakkeum Entryga formatting-e 불편할 때가 있습니다. Geureom d또 하나의 작은 step-eul 추가할 수 있습니다: Entry를 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 reversed on tie)
}
Igeot-do paipeline 철학에 잘 들어맞습니다: 다음 step을 더 쉽게 만들기 위한 또 하나의 단순한 data transformation입니다.
6. Formatting the report
Ije kkaji-neun “정직하게 세었다”는 계산 파트였습니다. Ije-buteo-neun user에게 결과를 보여주는 presentation 파트입니다: println으로 출력할 수 있는 예쁜 report string을 만들고 싶습니다. Yeogi-seo jung-yohan geon, counting logic과 formatting logic을 섞어서 spaghetti로 만들지 않는 것입니다. Ha-나-ui maine 다 넣더라도, 머릿속으로는 “여긴 계산”, “여긴 표시”를 분리해 두세요.
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
}
(word, count) deconstruction-i 동작하는 이유는 Pair가 component들을 지원하기 때문입니다. 결과적으로 compact하고 읽기 쉽습니다.
Light alignment with padEnd and padStart
Ijeon-e munjayeol padStart/padEnd
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
}
Igeot-eun ajik “big formatter”ga 아니라, console에서 보기 좋은 정도의 정돈된 출력입니다.
7. Building a mini Text Analyzer app
Ije uri-ga paipeline-eul gweonjanghaetdeon bomokjeog-e daehae hapseonghae bopsida: dan-gye-deul-eul han scenario로 이어 붙입니다. Aidi-eun ireon geos입니다: text를 읽고, normalize하고, tokenize하고, frequency를 세고, top‑N을 뽑고, report를 출력합니다. Ajik dan-gye-reul byeol도의 function으로 빼지 않겠습니다 — geugeon 다음 lecture에서 할 겁니다. Jigeum-eun transformation-i linearl하게 이어지는 느낌과, dan-gye마다 type이 “이사”하는 모습을 확인하는 게 더 중요합니다.
Version with intermediate val
import kotlin.text.Regex
fun main() {
println("Tekseuteureul ipryeokhaseyo:")
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)
}
I kodeu-neun “jom deo gireojiman”, saenggak-eul jeongjikage boyeojumnida: string-i list-ga 되고, list-ga map-i 되고, map-i top‑N-i 되고, top‑N-i text-ga 됩니다. Cheoeum si-do에서는 “1줄 super chain”보다 이 편이 더 낫습니다.
Chained version with scope functions
Ijeon lecture에서 scope functions-eul 이미 algo issdamyeon, gyeolgwa-reul deo “pipeline-like”하게 조립할 수 있습니다. Yeogi-seo alsoneun debugging print-reul 끼워 넣기에 편하고, main result를 망가뜨리지 않습니다 (원래 객체를 그대로 반환합니다).
import kotlin.text.Regex
fun main() {
val report = readln()
.let { Regex("""\s+""").replace(it.trim().lowercase(), " ") }
.also { println("Jeonggyuhwa-doem: $it") } // Jeonggyuhwa-doem: ...
.split(" ")
.filter { it.isNotBlank() }
.groupingBy { it }.eachCount()
.entries
.sortedByDescending { it.value }
.take(5)
.joinToString("\n") { "${it.key}: ${it.value}" }
println(report)
}
Hangsang ireon stileul sseuryeogo 하지 마세요. Chain-i 짧고 읽기 쉬울 때만 좋은 스타일입니다. Chain jung-gan-e “jigeum nae son-eul-eun mweoji?”ga heullimyeon (String? List? Map?), 멈추고 중간 val을 만들고, 이름도 제대로 붙이세요. Igeon programmer-reul 느리게 하는 게 아니라 — 디버깅을 빠르게 합니다.
8. Common mistakes when assembling a Text Analyzer pipeline
Mistake #1: tokenization before normalization.
Raw text-e daehae split(" ")buteo 하면, 빈 token과 이상한 결과가 거의 확정적으로 나옵니다. Munje-neun split이 아니라, whitespace가 여러 개일 수 있고 "\n", "\t" 같은 것들도 섞여 있기 때문입니다. Meonje whitespace를 han gae-ui space로 맞춘 다음에, 그 다음에 단어로 나누세요.
Mistake #2: forgot isNotBlank() filtering and got surprised by empty “words”.
Normalization-eul haedo border case-ga 남을 수 있습니다: empty input, 양 끝 공백, 예상치 못한 조합 등. 빈 token을 버리지 않으면 "" 같은 “dan-eo”가 생길 수 있고, 그게 갑자기 최빈 단어가 되어버릴 수도 있습니다 (공허는 정말 인기 많죠… 철학자들은 좋아하겠지만, users는 싫어합니다).
Mistake #3: trying to “sort a Map directly”.
Mapeun “key → value” 구조이고, sorting은 “ordered collection” 이야기입니다. 그래서 거의 항상 올바른 경로는 이렇습니다: freq.entries → sortedByDescending { it.value } → take(n). Igeol 당연한 것으로 받아들이면, top‑N이 더 이상 수수께끼가 아닙니다.
Mistake #4: mixing counting and formatting into one mess.
Frequency를 세면서 동시에 multiline string을 만들기 시작하면, kodeu-ga 금방 읽기 어려워집니다: 어디서 logic이 끝나고 어디서 “pretty output”이 시작되는지 불분명해집니다. Han gae-ui maine 다 쓰더라도, formatting 단계는 마지막 독립 단계로 분리하세요 (예: 별도의 report 변수).
Mistake #5: a chain that is “too clever”, where you lose track of types.
Scope functions과 operation chaining은 멋지지만, 사라지는 토끼 마술이 되어서는 안 됩니다. Chain 중간에 “지금 내 손에 뭐가 있지?”가 헷갈리면 (String? List<String>? Map<String, Int>?), 멈추고 intermediate val을 만들고, 정상적인 이름을 붙이세요. Igeon programmer-reul 느리게 하지 않습니다 — 디버깅을 빠르게 합니다.
GO TO FULL VERSION