import Foundation
/*
This program finds the N most frequently appearing words in a text
after removing stopwords. It demonstrates clean structure, clear
comments, and efficient use of Swift collections and sorting.
*/
// ---------------------------------------------------------------
// Tokenize text into words (simple whitespace split)
// ---------------------------------------------------------------
func tokenize(_ text: String) -> [String] {
var words: [String] = []
// Split on whitespace
for raw in text.split(whereSeparator: { $0.isWhitespace }) {
var w = String(raw)
// Remove punctuation at the edges
w = w.trimmingCharacters(in: .punctuationCharacters)
if !w.isEmpty {
words.append(w.lowercased())
}
}
return words
}
// ---------------------------------------------------------------
// Count word frequencies, skipping stopwords
// ---------------------------------------------------------------
func countWordFrequencies(_ words: [String], stopwords: Set<String>) -> [String: Int] {
var freq: [String: Int] = [:]
for w in words {
if !stopwords.contains(w) {
freq[w, default: 0] += 1
}
}
return freq
}
// ---------------------------------------------------------------
// Extract the top N most frequent words
// ---------------------------------------------------------------
func topN(_ freq: [String: Int], n: Int) -> [(String, Int)] {
// Convert dictionary to list of (word, count)
var items = freq.map { ($0.key, $0.value) }
// Sort by frequency descending, then alphabetically
items.sort {
if $0.1 != $1.1 {
return $0.1 > $1.1
}
return $0.0 < $1.0
}
return Array(items.prefix(n))
}
// ---------------------------------------------------------------
// Main
// ---------------------------------------------------------------
let text =
"C is a general-purpose programming language created in 1972 by " +
"Dennis Ritchie. C gives programmers direct access to the features " +
"of CPU. It has been and continues to be used to implement " +
"operating systems (especially kernels) and device " +
"drivers. C programming language used on computers ranging from " +
"supercomputers to microcontrollers and embedded systems."
let stopwords: Set<String> = [
"the","is","a","to","how","after","but","this","for","by","in",
"and","can","content","be","you","yes","no","next","about","used",
"access","been","continues"
]
// Tokenize
let words = tokenize(text)
// Count frequencies
let freq = countWordFrequencies(words, stopwords: stopwords)
// Get top n
let n = 7
let topn = topN(freq, n: n)
// Print results
print("Top \(n) most frequent non-stopwords:")
for (word, count) in topn {
print("\(word) : \(count)")
}
/*
run:
Top 7 most frequent non-stopwords:
c : 3
language : 2
programming : 2
systems : 2
1972 : 1
computers : 1
cpu : 1
*/